Realm是用来代替CoreData和SQLite的数据存储方式,支持的类型有Bool,Int16,Int32,Int64,Double,Float,String,Date,Data
-
在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<Dog>() }
在Realm中List相当于swift中的数组,要声明List中的数据类型。
-
增,删,改,查
-
添加一个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..<result.count { let p = result[i] print(p.name, p.dogs.count) } //查 let persons = realm.objects(Person.self).filter("age == 20") for i in 0..<persons.count { let p = persons[i] try! realm.write { p.name = "modifity" } print(p.name) }
-
Realm简单使用
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...