views:

62

answers:

2

What I'm trying is this:

1) Create a new manged object

2) Get it's temporary id with [myMO objectID];

3) Convert that ID to an NSURL, so I can save it for future reference:

NSManagedObjectID *moID = [myMO objectID];
NSURL *url = [moID URIRepresentation];

4) Save the managed object context

5) Some time later, fetch that object using the NSURL as ID

NSManagedObjectID *moID = [[context persistentStoreCoordinator] managedObjectIDForURIRepresentation:url];

And guess what: It does not work. I get an empty-stupid object back from

NSManagedObject *myOldMo = [context existingObjectWithID: moID error:&error];

But...as I said...the ID is temporary when creating an managed object. So it does make sense why this doesn't work at all. I must first save the context, and then I get a persistet ID. The real one. Right?

So is that the way to go?

1) Create the managed object

2) Save the context

3) Get the ID as NSURL

4) any time later, for example on your next birthday, access the managed object with the NSURL ;-)

I try to dream of NSManagedObjectID like a DB id which I can write on some yellow postIt sheet and glue on the middle of my monitor, so I refer back to it after lunch. You know... at least like in the old days where we used databases over telnet and executed SQL commands manually to query order information and stuff like that. The ID was the most important and significant thing, all the time.

But Core Data has this somewhat strange NSManagedObjectID thing.

What are your secret strategies? Do you actually recognize many use cases where you would need that NSManagedObjectID? Or is that something I could easily forget with no pain afterwards?

A: 

the funniest read ever... I second you. There are multiple use cases where you would LOVE to have this ID without having to save or better without having to change it because guess what someone else saved the DB in the mean time.

tom
A: 

I'm not sure that it's such a big secret. The documentation describes the way to get permanent IDs for managed objects from the NSManagedObjectContext:

- (BOOL)obtainPermanentIDsForObjects:(NSArray *)objects error:(NSError **)error

http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSManagedObjectContext_Class/NSManagedObjectContext.html#//apple_ref/occ/instm/NSManagedObjectContext/obtainPermanentIDsForObjects:error:

ohhorob