添加库
pod 'Realm'
pod 'RealmSwift'
配置数据信息
在AppDelegate的application,didFinishLaunchingWithOptions方法中添加以下方法configRealm()
fileprivate func configRealm() {
// 如果要存储的数据模型属性发生变化,需要配置当前版本号比之前大
let dbVersion : UInt64 = 4
let docPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] as String
let dbPath = docPath.appending("/defaultDB.realm")
let config = Realm.Configuration(fileURL: URL.init(string: dbPath), inMemoryIdentifier: nil, syncConfiguration: nil, encryptionKey: nil, readOnly: false, schemaVersion: dbVersion, migrationBlock: { (migration, oldSchemaVersion) in
}, deleteRealmIfMigrationNeeded: false, shouldCompactOnLaunch: nil, objectTypes: nil)
Realm.Configuration.defaultConfiguration = config
Realm.asyncOpen { (realm, error) in
if let _ = realm {
// print("Realm 服务器配置成功!")
}else if let error = error {
print("Realm 数据库配置失败:\(error.localizedDescription)")
}
}
}
使用
新建一个模型
class PVCount: Object {
@objc dynamic var id = 0
@objc dynamic var count = 0
@objc dynamic var time = 0
override static func indexedProperties() -> [String] {
return ["id"]
}
}
添加
let realm = try! Realm()
try! realm.write {
let pvCount = PVCount(value: ["id" : model.news_id, "count": 1, "time": 1])
realm.add(pvCount)
}
删除
let realm = try! Realm()
try! realm.write {
let pvs = realm.objects(PVCount.self)
realm.delete(pvs)
}
查询
let realm = try! Realm()
try! realm.write {
let pvs = realm.objects(PVCount.self)//查询所有
let pvCounts = realm.objects(PVCount.self).filter("id = %@", model.news_id)//根据 id 查询
//let predicate = NSPredicate(format: "id < 5 AND count > 10)//复合查询
//let predicate = NSPredicate(format: "id < 5 AND name BEGINSWITH '张'")
}
修改
let realm = try! Realm()
try! realm.write {
let pvCounts = realm.objects(PVCount.self).filter("id = %@", model.news_id)
let pv = pvCounts.first
//let pvCount = pvCounts[0]
pvCount.count = pvCount.count+1
}
以上就是Realm数据在 swift 中的基本操作(增删查改),希望对您有所帮助