Currently I'm trying to save an NSRect
to my user defaults. Right now I'm using an NSValue
to wrap it as an object then save it into the user defaults as an object with the following code:
[userDefaults setObject:[NSValue valueWithRect:rect forKey:@"Key"]];
However, when I run it, I get an error that says:
[NSUserDefaults setObject:forKey:]: Attempt to insert non-property value 'NSRect: {{0, 0}, {50, 50}}' of class 'NSConcreteValue'.
Does anyone know how I can fix this?
NSValue
is not supported by the user defaults.
The value parameter can be only property list objects: NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. For NSArray and NSDictionary objects, their contents must be property list objects.
You need to archive the value into data then unarchive it when you access it.
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSRect rect = { 0, 0, 10, 20 };
NSValue *value = [NSValue valueWithRect:rect];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:value];
[userDefaults setObject:data forKey:@"key"];
[userDefaults synchronize];
data = [userDefaults objectForKey:@"key"];
NSValue *unarchived = [NSKeyedUnarchiver unarchiveObjectWithData:data];
NSLog(@"%@", unarchived);