我有SaveDataToRealm类。在这个课程中,我试图将数据存储在领域中。但我无法得到它。当我在写入后打印领域对象时,它显示的对象没有我试图写的值。
class SaveDataToRealm: BaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
saveSessionData()
}
// MARK:- save session and Close session
func saveSessionData() {
let realm = try! Realm()
let localSession = TempRingSessionObject()
if isLiveSession{
sessionId = RandomStringGenerator.sharedInstance.getUniqueSessionString()
localSession.sessionId = sessionId!
} else{
localSession.class_id = courseSetupDetails["class_id"] as! String
}
try! realm.write {
realm.add(localSession)
}
}
通过使用saveSessionData()
函数,我正在初始化Realm。在closeSelfSession()
函数中,我试图将数据存储到Realm中。
func closeSelfSession(currentTimeStamp:String) {
let realm = try! Realm()
if !(sessionId ?? "").isEmpty{
let session = realm.objects(TempRingSessionObject.self).filter("sessionId contains '\(String(describing: self.sessionId))'").last
try! realm.write {
session?.score = "60"
session?.timeOfSession = currentTimeStamp
session?.tempSessionData.append(objectsIn:realm.objects(TempRingDataObject.self).filter("tag = '\(tagString)'"))
}
} else{
let session = realm.objects(TempRingSessionObject.self).filter("sessionId contains '\(self.courseSetupDetails["class_id"] as! String)'").last
try! realm.write {
session?.tempSessionData.append(objectsIn: realm.objects(TempRingDataObject.self).filter("tag = '\(tagString)'"))
session?.timeOfSession = currentTimeStamp
session?.score = "75"
}
}
}
我做错了什么? 谢谢!
答案 0 :(得分:0)
您用于过滤的NSPredicate
都存在缺陷。
您永远不应该使用String(describing:)
来比较变量,因为根据确切的类型,它可能会产生意外的结果。此外,在谓词中使用单引号时,您可以告诉编译器查找确切的结果,而不是查找变量的值。在使用"\(variable)"
时,您也不应该使用字符串插值(NSPredicate
),您应该使用%@
格式说明符。
let session = realm.objects(TempRingSessionObject.self).filter("sessionId contains '\(String(describing: self.sessionId))'").last
实际应该是
let session = realm.objects(TempRingSessionObject.self).filter("sessionId CONTAINS @%",self.sessionID).last
此谓词realm.objects(TempRingDataObject.self).filter("tag = '\(tagString)'")
应为
realm.objects(TempRingDataObject.self).filter("tag = %@",tagString)
你的最后一个谓词,
realm.objects(TempRingSessionObject.self).filter("sessionId contains '\(self.courseSetupDetails["class_id"] as! String)'"
应该是
realm.objects(TempRingSessionObject.self).filter("sessionId CONTAINS %@",self.courseSetupDetails["class_id"])