How to store a NSManagedObjectID persistently?
为避免成为 XY 问题,这里有一些背景:
我的应用程序允许用户创建和保存很多设置,有点像 Xcode 的字体和颜色选择器:
这是因为用户可以设置很多东西。只需点击已保存的设置而不是再次设置所有这些设置会更容易。
我使用 Core Data 来存储用户保存的设置。用户创建的每个设置都是
我的第一个想法是将
,否则我无法存储它
A default object must be a property list, that is, an instance of (or for collections a combination of instances of): NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary.
然后我尝试存储
1 | NSData(contentsOfURL: selectedOption!.objectID.URIRepresentation()) |
但是初始化程序以某种方式失败了。
现在我意识到这是一个愚蠢的想法,因为即使我可以将其转换为
根据this question,OP似乎能够存储对象id:
I store the selected theme objectID in NSUserDefaults so that when the app restarts, the selected theme will still be intact.
我该怎么做呢?
1 2 | public func setURL(url: NSURL?, forKey defaultName: String) public func URLForKey(defaultName: String) -> NSURL? |
允许存储和检索
通过
被透明地处理。来自文档:
When an NSURL is stored using
-[NSUserDefaults setURL:forKey:] , some adjustments are made:Any non-file URL is written by calling +[NSKeyedArchiver archivedDataWithRootObject:] using the NSURL instance as the root
object.... When an NSURL is read using
-[NSUserDefaults URLForKey:] , the following logic is used:If the value for the key is an NSData, the NSData is used as the argument to +[NSKeyedUnarchiver unarchiveObjectWithData:] . If the NSData can be unarchived as an NSURL, the NSURL is returned otherwise nil is returned....
所以保存被管理对象 ID 只是简单地做为
1 2 | NSUserDefaults.standardUserDefaults().setURL(object.objectID.URIRepresentation(), forKey:"selected") |
并检索对象 ID 和对象,例如:
1 2 3 4 5 6 7 | if let url = NSUserDefaults.standardUserDefaults().URLForKey("selected"), let oid = context.persistentStoreCoordinator!.managedObjectIDForURIRepresentation(url), let object = try? context.existingObjectWithID(oid) { print(object) // ... } |
有关保存所选设置的替代方法,请参阅上面的评论。