Search code examples
ioscocoacore-datafoundationnsvaluetransformer

what's the correct way to store an NSURL in Core Data?


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?


Solution

  • 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]];