views:

45

answers:

3

I want to have table in CoreData that holds a list of other CoreData objects I have accessed, for instance I have Clients and I want a table RecentClients that is simply holding this list and the date they were accessed.

Can I store the objectID and then do a fetch request based on that?

EDIT: See Ben's answer below and then go here: http://cocoawithlove.com/2008/08/safely-fetching-nsmanagedobject-by-uri.html

A: 

You could just create the RecentClients as another entity in your Core Data model. It would then have a one to many relationship with the Client entity.

Chris Gummer
that is what I am doing, but I need to look at just the recent clients table and have a way to uniquely identify the entity, that's why I asked about the objectID.
Slee
+3  A: 

You'll want to convert the NSManagedObjectID to a string by calling its -URIRepresentation method. You can then convert the string back to an NSManagedObjectID using NSPersistentStore's -managedObjectIDForURIRepresentation: method.

If you store the strings, you should be able to do what you're describing, though you won't use a fetch request; you'll use -[NSManagedObjectContext objectWithID:]

Ben Gottlieb
Very nice. Would you use these if you want to persist from one run to the next? Obviously one could, but I wonder if you would then suggest modifying data model. This has been a peripheral issue for me, hence the interest. (I don't think that this merits its own 'question'.)
westsider
objectIDs are persistent. If you write a URIRepresentation to disk and, on a subsequent run, use it to look up the objectID, you'll get back the same ID that was used to create the URI in the first place, and (assuming the object still exists) this objectID will still identify the same original managed object.
Kevin Ballard
objectIDs are persistent only after the object has been saved for the first time. The objectID for a newly created object changes when it is saved the first time.
Aderstedt
works perfect - thank you!
Slee
Aderstedt brings up a very good point, which can cause problems if you're not aware of it. I ran into a mess of issues when I was tracking objectIDs before they were saved to the persistent store. Only use these for objects that have been saved to the store.
Brad Larson
+2  A: 

How are you planning on storing the access date? If you make it an attribute of your Client entity, you can bump it each time the object is accessed and then use an NSFetchedResultsController that fetches Clients ordered by the access date. The downside is, of course, that you're modifying the instance every time you access it, which may not be ideal.

Kevin Ballard