Using a concise form of NSManagedObjectID URI?

后端 未结 1 1549
伪装坚强ぢ
伪装坚强ぢ 2021-02-01 08:45

In my app, I\'m using Core Data alongside an additional sqlite database that doesn\'t use Core Data. In this additional database, I have columns that store references to N

相关标签:
1条回答
  • 2021-02-01 09:39

    You could try setting the "Allows External Storage" flag on the attributes that contain your large chunks of data, and see if that eliminates the need for a separate, directly-managed database.

    Otherwise, URIRepresentation returns an NSURL, so no "icky" string manipulation is necessary. Just use the NSURL methods. ;^) Here's how you break it down:

    NSURL *instanceURL = instance.objectID.URIRepresentation;
    NSURL *classURL = [instanceURL URLByDeletingLastPathComponent];
    NSString *classString = [classURL absoluteString];
    NSString *instanceId = [instanceURL lastPathComponent];
    

    And here's how you put it back together later:

    NSURL *reconstructedClassURL = [NSURL URLWithString:classString];
    NSURL *reconstructedInstanceURL = [reconstructedClassURL
        URLByAppendingPathComponent:instanceId];
    NSManagedObjectID *objectID = [moc.persistentStoreCoordinator
        managedObjectIDForURIRepresentation:reconstructedInstanceURL];
    NSManagedObject *reconstructedInstance = [moc objectWithID:objectID];
    

    Note that since the URIRepresentation is documented to be "archivable", there's no harm in rebuilding one from components that were given to you by Core Data. Core Data doesn't know that you took it apart and put it back together.

    However, Apple is allowed to change the format returned by URIRepresentation in the future, as long as managedObjectIDForURIRepresentation: continues accepting the old format. That means the code above that breaks apart the URIRepresentation could stop working someday.

    0 讨论(0)
提交回复
热议问题