I have a simple iPhone app which accesses some remote data on start-up then asks the user to select one of the options chosen, but this happens each time the app starts, and I want the app to remember that choice for next time around, how can I persist this object using Core Data?
Im very new to Core Data, and I figure its something to do with adding an object to the NSManagedObjectContext
but im not sure if there is a way to store one object against a key or something so that I can check if its been chosen before quickly to avoid doing the remote call...
EDIT
Ok, seems like NSUserDefaults
is the way to go here, but I have a small issue, my custom class is extends NSManagedObject
which I hear is a bit tough to store an instance of in NSUserDefaults, so I wrote a little converter that takes each property of the class and puts it in NSUserDefaults seperatly under different keys.
like so:
-(void)saveDeviceForUser:(Device*) device
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *encodedActive = [NSKeyedArchiver archivedDataWithRootObject:device.active];
[defaults setObject:encodedActive forKey:@"UsersDevice_Active"];
//and so on for each property of the Device object
}
then I retrieve my object in a similar fashion:
-(Device*)loadDeviceForUser
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *encodedActive = [defaults objectForKey: @"UsersDevice_Active"];
NSNumber* unarchivedActive = (NSNumber*)[NSKeyedUnarchiver unarchiveObjectWithData: encodedActive];
Device *d = [[Device alloc] init];
d.active = unarchivedActive;
return d;
}
But, when I get to the line above of d.active = unarchivedActive
I get an error:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Device setActive:]: unrecognized selector sent to instance 0xac0be10'
My class properties are setup using @dynamic and not @synthesize, so do I have to implement the setters and getters in order for this to work? Will that upset Core Data in any way?
I hope that makes sense
Cheers, Mark