views:

53

answers:

1

I'm using Core data and region monitoring. The only way to distinguish between monitored regions is with a NSString for identifier. I'd love to use NSManagedObjectID, but I can't get it to work.

What I've tried:

NSURL *objURL = [managedObjectID URIRepresentation];
NSError *err;
NSString *identifier = [NSString stringWithContentsOfURL:myURL
                                                encoding:NSASCIIStringEncoding
                                                   error:&err];

the error I get is:

The operation couldn’t be completed. (Cocoa error 256.)

Any ideas of a better way? Or what I'm doing wrong?

+3  A: 

You should not get the contents of the URI of the NSManagedObjectID. stringWithContentsOfURL:encoding:error: tries to load the resource pointed by the URI; it uses appropriate operations depending whether the URI is http or file or etc. But it doesn't know how to deal with an NSManagedObjectID URI, and it's not what you want to do anyway.

Instead, I guess what you want to do is

 NSString*identifier=[objURL absoluteString];

This gives a string representation of the URL.

I'll add Marcus's comment so that everyone will notice:

Be aware that the objectID can and does change, especially when a migration occurs. Do not rely on that value to be consistent between one launch of the application and the next.

Yuji
perfect. Thanks!
Derrick
Be aware that the objectID can and does change, especially when a migration occurs. Do not rely on that value to be consistent between one launch of the application and the next.
Marcus S. Zarra
Thanks for pointing it out. I'll add it so that somebody who reads this entry but not the comments section won't miss it...
Yuji
Thanks @Marcus for the heads up. What about the `isTemporary:` method? The apple docs make it seem as if it returns NO you're fine.http://developer.apple.com/mac/library/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSManagedObjectID_Class/Reference/NSManagedObjectID.html#//apple_ref/occ/instm/NSManagedObjectID/isTemporaryIDI can definitely see that occurring on a migration though.
Derrick
Temporary vs. permanent is different than the change during a migration. Even a permanent ID will change during migration.
Marcus S. Zarra