关于ios:如何持久存储一个NSManagedObjectID?

How to store a NSManagedObjectID persistently?

为避免成为 XY 问题,这里有一些背景:

我的应用程序允许用户创建和保存很多设置,有点像 Xcode 的字体和颜色选择器:

enter

1
NSData(contentsOfURL: selectedOption!.objectID.URIRepresentation())

但是初始化程序以某种方式失败了。

现在我意识到这是一个愚蠢的想法,因为即使我可以将其转换为 NSData,我也无法将 NSData 转换回 NSManagedObjectID

根据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.

我该怎么做呢?


NSUserDefaults 有"便利方法"

1
2
public func setURL(url: NSURL?, forKey defaultName: String)
public func URLForKey(defaultName: String) -> NSURL?

允许存储和检索 NSURL 就像获得的一样
通过 URIRepresentation()NSData 之间的转换
被透明地处理。来自文档:

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)
        // ...
    }

    有关保存所选设置的替代方法,请参阅上面的评论。