NSManagedObjectID into NSData

前端 未结 6 2154
一生所求
一生所求 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 06:55

    To get an archived URI corresponding to a NSManagedObject's objectID:

    NSManagedObject* myMO;
    ...
    NSURL *uri = [[myMO objectID] URIRepresentation];
    NSData *uriData = [NSKeyedArchiver archivedDataWithRootObject:uri];
    

    In order to get back to an instance of the original managed object, you need a CoreData stack with the persistent store holding that instance already added to the NSPersistentStoreCoordinator. Then:

    NSData *uriData;
    NSPersistentStoreCoordinator *psc;
    NSManagedObjectContext *moc; //with moc.persistentStoreCoordinator = psc.
    ...
    NSURL *uri = [NSKeyedUnarchiver unarchiveObjectWithData:uriData];
    NSManagedObjectID *moID = [psc managedObjectIDForURIRepresentation:uri];
    NSManagedObject *myMO = [moc objectWithID:moID];
    

提交回复
热议问题