Pergunta

I'm trying to archive / unarchive NSManagedObjectIDs in Core Data objects so that next time my app starts up I can retrieve these IDs and use them to fetch specific objects.

I tried "archiving" the ID like this:

//defaultConfiguration is an NSManagedObject defined elsewhere and it works just fine...    
// and newObject is also properly initialized, bound to a context,etc...

ArchivedID* newID = [NSEntityDescription insertNewObjectForEntityForName:@"ArchivedID" inManagedObjectContext:managedObjectContext];
[self.defaultConfiguration addArchiveIDObject:newID];
newID.idURI = [[newObject objectID] URIRepresentation];
[managedObjectContext save:&error]; 

And then unarchiving like this (I'm just going for [anyObject] cause i'm testing and there's only one at this point):

NSManagedObjectID* ID = [managedObjectContext.persistentStoreCoordinator managedObjectIDForURIRepresentation:[defaultConfiguration.archiveID anyObject]];

But when I try getting the URL back like above, I get the following exception:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ArchivedID relativeString]: unrecognized selector sent to instance 0x7f59f20'

The attribute in the entity was set up through Xcode to "transformable" and I left the transformer value field in Xcode empty since the Core Data documentation seems to imply if empty it's use the default transformer.

What am I doing wrong?

Foi útil?

Solução 2

Ok... It's been 14hrs straight of coding.. I'm an.. eh.. idiot:

I forgot to access the attribute in the ArchivedID object. That is:

NSManagedObjectID* ID = [managedObjectContext.persistentStoreCoordinator managedObjectIDForURIRepresentation:[defaultConfiguration.archiveID anyObject]];

should be

NSManagedObjectID* ID = [managedObjectContext.persistentStoreCoordinator managedObjectIDForURIRepresentation:[[defaultConfiguration.archiveID anyObject] idURI]];

Outras dicas

It's possible you can solve this problem without storing URLs. Consider adding a boolean flag to your model and marking the objects you wish to retrieve as true, then fetch flagged objects next time your app starts.

However, you could try getting the string version of the URL with -absoluteString and storing that.

Hmmm. Seems like there is a much simpler way to do this with CoreData. Remember, CoreData is an object graph. It's good at keeping track of relationships.

Why not just have an entity in CoreData that keeps a one-to-many relationship to the objects you like? Then, you can just insert/remove/search/iterate/whatever over the collection of objects.

I like what @kevboh suggested. You might also consider storing the objectIDs of specific NSManagedObjects in NSUserDefaults. E.g.:

[[NSUserDefaults standardUserDefaults] setObject:featuredNSManagedObjectIDArray
                                          forKey:@"FeaturedNSManagedObjectIDs"];
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top