NSManagedObjectID into NSData

前端 未结 6 2157
一生所求
一生所求 2020-12-30 06:27

I found this wonderful NSManagedObjectID. This would be very good for referencing an Entity/NSManagedObject/NSEntityDescription, right?
Let\'s get an ID from an entity:<

6条回答
  •  死守一世寂寞
    2020-12-30 07:07

    Here's the cleanest and shortest way I've found to do this currently, using the setURL and getURL methods added in 4.0 to avoid extra calls to NSKeyedUnarchiver and NSKeyedArchiver:

    Setter:

     + (void)storeSomeObjectId:(NSManagedObjectID *)objectId
     {
         [[NSUserDefaults standardUserDefaults] setURL:[objectId URIRepresentation] 
                                                forKey:@"someObjectIdKey"];
         [[NSUserDefaults standardUserDefaults] synchronize];
     }
    

    Getter:

     + (SomeManagedObject *)getObjectByStoredId
     {
         NSURL *uri = [[NSUserDefaults standardUserDefaults] URLForKey:@"someObjectIdKey"];
         NSManagedObjectID *objectId = [self.persistentStoreCoordinator managedObjectIDForURIRepresentation:uri];
         SomeManagedObject *object = [self.managedObjectContext objectWithID:objectId];
     }
    

提交回复
热议问题