我遇到一个非常奇怪的错误,我有一个PodEvent类型的数组,使用第二个函数时,我得到了另一个我要转换的数组,当我对转换后的数组进行打印时,结果将向我显示对象的所有对象。板...
PodEvent {
eventID = 2;
podID = 1;
drinkDate = 2018-09-25 10:00:00 +0000;
actualDrinkingTime = (null);
keyDate = 2018-09-25 13:00;
rawState = Forgotten;
}
但是,当我要访问对象的值时,它将作为默认值返回给我!例如:
print(self.podEvents[1].eventID)
print(self.podEvents[1].podID)
输出:
-1
-1
这是我的课:
class PodEvent: Object {
@objc var eventID: Int = -1
@objc var podID: Int = -1
@objc var drinkDate: Date = Date()
@objc var actualDrinkingTime: Date? = Date()
var state: PodState = .future
@objc var keyDate: String = ""
@objc private var rawState: String!
convenience init(eventID: Int, podID: Int, drinkDate: Date, actualDrinkingTime: Date?, state: PodState){
self.init()
self.eventID = eventID
self.podID = podID
self.drinkDate = drinkDate
self.actualDrinkingTime = actualDrinkingTime
self.state = state
self.rawState = state.state
}
func setState(state: PodState){
self.state = state
rawState = state.state
}
override class func primaryKey() -> String? {
return "keyDate"
}
这个错误很奇怪
我的代码来获取我的数组:
//Fetch pod history in internal database
self.databaseManager.fetch(object: PodEvent.self, predicate: nil, sortedBy: "keyDate", ascending: true) { success, results, error in
guard error == nil else {
Alerts.alertMessage(for: self, title: "ERROR".localized,
message: error!.localizedDescription,
closeHandler: nil)
return
}
self.podEvents = (results as! [PodEvent])
self.pods = pods
print(self.podEvents[1].eventID)
print(self.podEvents[1].podID)
}
和:
func fetch(object: Object.Type, predicate: NSPredicate?, sortedBy: String, ascending: Bool, completion: DatabaseCompletion?) {
do {
let realm = try Realm()
let objects: Results<Object>!
if let predicate = predicate {
objects = realm.objects(object).filter(predicate).sorted(byKeyPath: sortedBy, ascending: ascending)
} else {
objects = realm.objects(object).sorted(byKeyPath: sortedBy, ascending: ascending)
}
let objectsArray = Array(objects)
completion?(true, objectsArray, nil)
} catch let error {
print("Could not write object (type \(object)) to Realm:", error.localizedDescription)
completion?(false, nil, error)
}
}
即时通讯使用领域
答案 0 :(得分:1)
您的对象定义有缺陷,您需要在所有持久属性中添加dynamic
关键字。
class PodEvent: Object {
@objc dynamic var eventID = -1
@objc dynamic var podID = -1
@objc dynamic var drinkDate = Date()
@objc dynamic var actualDrinkingTime: Date? = Date()
var state: PodState = .future
@objc dynamic var keyDate = ""
@objc dynamic private var rawState: String!
...
}