迅捷3将字符串转换为objectID

Gho*_*108 5 macos swift3 xcode8

我使用swift 3和nsoutlineview。我想将核心数据记录的objectID保存到文本字段中。所以我必须将其转换为字符串:

txtFied.stringValue = "\(CoreData[outlineView.selectedRow].objectID)"
Run Code Online (Sandbox Code Playgroud)

如何将其转换回NSManagedObjectID?

Jos*_*den 7

我通过持久性存储协调器的managedObjectID(forURIRepresentation:)方法完成了此操作,如下所示:

    // Convert NSManagedObjectID to a string, via the uriRepresentation method.
    let objectIDString = <your managed object ID>.uriRepresentation().absoluteString
    ...
    // Use the persistent store coordinator to transform the string back to an NSManagedObjectID.
    if let objectIDURL = URL(string: objectIDString) {
        let coordinator: NSPersistentStoreCoordinator = <reference to your persistent store coordinator>
        let managedObjectID = coordinator.managedObjectID(forURIRepresentation: objectIDURL)
    }
Run Code Online (Sandbox Code Playgroud)