1.创建数据模型
import Foundation
import RealmSwift
class Dog: Object {
@objc dynamic var name = ""
@objc dynamic var age = 0
}
class Person: Object {
@objc dynamic var ID = 0
@objc dynamic var name = ""
@objc dynamic var age = 0
var dogs = List<Dog>() //model 嵌套
//重写primaryKey方法
override static func primaryKey() -> String? {
return "ID"
}//主键
}
2.创建数据模型对象
let myDog = Dog()
myDog.name = "Rex"
myDog.age = 1
print("name of dog: \(myDog.name)")
3.数据库操作(增删改查)
任何时候都需要获取Realm实例,每个线程只需要使用一次即可
// 获取默认的 Realm 数据库
let realm = try! Realm()
//打印地址
print(realm.configuration.fileURL!)
查询数据
- 普通查询
let lists = realm.object(Person.self)
- 逐渐查询:根据逐渐查询某张表的某条数据,模型必须包含主键,否则会崩溃。
let tem = realm.object(ofType: Person.self, forPromaykey: "1")
- 条件查询: 根据断言字符串 或者 NSPredicate 谓词 查询某张表中的符合条件数据
let tem = realm.object(Person.self).filter("name == %@", "哈哈"
let predicate = NSPredicate(format: "name contains %@ and age == ","哈哈",1)
let temps = realm.objects(Person.self).filter(predicate)
数据排序
/* 根据搜索内容排序 默认是升序排序*/
let lists = realm.objects(Person.self).sorted(byKeyPath: "age")
/* 根据搜索内筒降序排序*/
let lists = realm.objects(Person.self).sorted(byKeyPath: "age", ascending: false)
增加数据
//替换存在的历史记录
let model = Person(value: ["张三",2])
let lists = realm.objects(Person.self)
if lists.count > 0 {
for temp in lists {
if temp.name == model.name && temp.age == model.age{
realm.delete(temp)
break
}
}
}
try! realm.write {
realm.add(model)
}
删除数据
/* 删除指定类型的数据*/
let tem = realm.objects(Person.self).filter("age == %lu", isNotHomeComing)
try! realm.write {
rel.delete(tem)
}
resetSubViews()
self.tableView?.reloadData()
修改数据
let lists = realm.objects(Person.self)
for model in lists{
if model.name == "张三" {
try! rel.write {
model.name = ""
}
break
}
}
- 根据主键更新
如果在model类型中设置了主键的话,那么你可以使用realm().add(_:update:)