Realm简单使用

  1. Realm是用来代替CoreData和SQLite的数据存储方式,支持的类型有Bool,Int16,Int32,Int64,Double,Float,String,Date,Data

  2. 在swift中,创建一个Dog类,继承自Object,如下所示:

     class Dog: Object {
     @objc dynamic var name = ""
     @objc dynamic var age = 0
     @objc dynamic var key = 0
     //主键
     override static func primaryKey() -> String? {
     return "key"
     }
     }
    

    然后在创建一个Person类,同样继承自Object类,在Person类中可能拥有多个dog属性,如下:

     class Person: Object {
     @objc dynamic var name = ""
     @objc dynamic var age = 0
     @objc dynamic var isEat = false
     var dogs = List()
     }
    

    在Realm中List相当于swift中的数组,要声明List中的数据类型。

  3. 增,删,改,查

    • 添加一个dog对象

        let realm = try! Realm()
        let myDog = Dog()
        
        myDog.name = "canader"
        myDog.key = 1
        myDog.age = 20
        
        //增
        try! realm.write {
        realm.add(myDog)
        }
        
        //删
        try! realm.write {
        
            //删除myDog
        realm.delete(myDog)
        //删除所有
        realm.deleteAll()
        }
      
        //改
        try! realm.write {
        myDog.name = "JACK"
        }
        
        //通过主键更新
         try! realm.write {
            //如果有主键为默认值的对象,那么久更新
        realm.add(myDog, update: true)
        }
        
        //通过键值编码更新属性
        try! realm.write {
        myDog.setValue("Rose", forKeyPath: "name")
        }
        
        //查
        //获取所有的dog属性
        let result = realm.objects(Dog.self)
        
        //过滤获取到的Dog属性
        let result = realm.objects(Dog.self).filter("age > 0")
      
    • 添加一个person对象

        //增
        let dog2 = Dog()
        dog2.name = "dog2"
        dog2.age = 10
        dog2.key = 2
      
        let person1 = Person()
        person1.name = "wangwu"
        person1.age = 20
        person1.isEat = true
        //给Person的dogs属性添加对象
        person1.dogs.append(myDog)
        person1.dogs.append(dog2)
        try! realm.write {
        realm.add(person1)
        }
        
        
        //删
        try! realm.write {
        realm.delete(persons)
        }
        
        
        //改
        let result = realm.objects(Person.self)
        print(result.count)
        for i in 0..

你可能感兴趣的:(Realm简单使用)