How to get object id from url?

my code is below:

NSURL *urlID = [objID URIRepresentation];
    NSString *strID = [urlID absoluteString];
    NSDictionary *infoDict = [NSDictionary dictionaryWithObjectsAndKeys:strID, @"objectID", nil];
    localNotification.userInfo = infoDict;

then I want it to turn out like this:

NSString *strID = [notification.userInfo objectForKey:@"objectID"];
NSURL *urlID = [[NSURL alloc] initWithString:strID];
NSManagedObjectID *objID = [[NSPersistentStoreCoordinator alloc] managedObjectIDForURIRepresentation:urlID];

but objID is zero. nothing bad? how to do it? thank!

+5
source share
1 answer

If this is your actual code, then the line below is suspicious

NSManagedObjectID *objID = [[NSPersistentStoreCoordinator alloc] managedObjectIDForURIRepresentation:urlID];

You assign a new NSPsistentStoreCoordinator, uninitialized, without any stores added to it. According to the documentation, it will return zero if no matching stores are found.

If you have a managed entity context, the following should work

NSManagedObjectID *objId = [[[self managedObjectContext] persistentStoreCoordinator] managedObjectIDForURIRepresentation:urlID];

otherwise, I agree with svena's answer.

+7
source

All Articles