我正在开发一个需要存储服药时间的应用程序。通过通知操作,我想将服用此药丸的时间存储在 CoreData 中。是否可以像这样将其用作数组?我的实体:
和通知操作:
func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forLocalNotification notification: UILocalNotification, completionHandler: () -> Void) {
if identifier == "remindLater" {
print("remindLater")
notification.fireDate = NSDate().dateByAddingTimeInterval(60)
UIApplication.sharedApplication().scheduleLocalNotification(notification)
} else if identifier == "takePill" {
print("Pill taken")
do {
let results = try managedObjectContext.executeFetchRequest(fetchRequest)
for medicine in results {
medicine.timeArray.append(NSDate())
}
} catch let error as NSError {
print(error.userInfo)
}
}
completionHandler()
}
最佳答案
通过归档到 NSData,可以将任何符合 NSCoding 的类型存储在 Core Data Transformable 属性中。 因此,您可以将数组存储在 Core Data 中。
以下是在核心数据实体的属性中归档数据的示例,其中 myEntity
是 NSManagedObject
引用。
myEntity.setValue(NSKeyedArchiver.archivedDataWithRootObject(timeArray),
forKey: "timeArray")
一旦您拥有对托管对象的引用(例如从获取请求返回的对象),就可以使用相应的取消归档操作来检索数据。
let myTimeArray = NSKeyedUnarchiver.unarchiveObjectWithData(
myNSManagedObject.valueForKey("timeArray") as! NSData)
关于ios - 将 NSDate 存储为 CoreData 中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33701877/