Question

I'm developing an app that uses CoreData. For the purpose of my app, I would like to save the managedObjectId of an object (in a plist file) in order to retrieve this object on the next app launch.

Following some reseaches, I tried :

myDictionary setObject:self.myPerson.objectID.URIRepresentation.absoluteString forKey:@"lastSelectedPerson"];
// Then I write the dictonary into a file
// I get a value like "x-coredata://8CF33004-BADD-402D-9AA5-115A030F901A/Person/p1"

myPerson is a object that has been save in the managedObjectContext.

Next I have tried to retrieve the objectID, but I get a nil value with this code :

// After retrieving the dictonary from the plist file
NSString * lastSelectedPersonId = [myDictionary objectForKey:@"lastSelectedPerson"];
NSManagedObjectID * objectID = [self.managedObjectContext.persistentStoreCoordinator managedObjectIDForURIRepresentation:[NSURL URLWithString:lastSelectedPersonId]];
self.myPerson = (Person *)[self.managedObjectContext existingObjectWithID:objectID error:&error];

Do you have any suggestion ? Thanks.

Was it helpful?

Solution

To restore object on next launch you can alternatively try following:

  1. Save objectID to NSUserDefaults:

    [[NSUserDefaults standardUserDefaults] setObject:self.myPerson.objectID forKey:@"lastSelectedPerson"]; 
    [[NSUserDefaults standardUserDefaults] synchronize];
    
  2. On the next launch get value from NSUserDefaults:

    NSNumber *lastSelectedPersonID = [[NSUserDefaults standardUserDefaults] objectForKey:@"lastSelectedPerson"];
    
  3. Query Core Data store to get object:

    - (Person *)personWithID:(NSNumber *)personID {
    
    Person *person = nil;
    
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    request.entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.managedObjectContext];
    request.predicate = [NSPredicate predicateWithFormat:@"objectID == %@", personID];
    
    NSError *error = nil;
    NSArray *persons = [self.managedObjectContext executeFetchRequest:request error:&error];
    
    person = [persons lastObject];
    
    return person;
    }
    

OTHER TIPS

I had a similar problem that I was creating a managed object and pulling off the object id and it hadn't been saved to disk yet. If that is the case the object id is a "temporary" id. I would check using: [NSManagedObjectID isTemporaryID]

If it returns that it is a temporary id you need to save the object and make sure you have a permanent id.

Documentation: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSManagedObjectID_Class/Reference/NSManagedObjectID.html#//apple_ref/occ/instm/NSManagedObjectID/isTemporaryID

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top