TheAmateurProgrammer
TheAmateurProgrammer

Reputation: 9392

Saving NSRect to NSUserDefaults

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?

Upvotes: 11

Views: 6224

Answers (2)

Mundi
Mundi

Reputation: 80265

Here is a much simpler solution, using NSString:

// store:
[[NSUserDefaults standardUserDefaults] 
   setValue:NSStringFromCGRect(frame) forKey:@"frame"];

// retrieve:
CGRect frame = CGRectFromString(
   [[NSUserDefaults standardUserDefaults] stringForKey:@"frame"]);

Swift 4

// store
UserDefaults.standard.set(NSStringFromCGRect(rect), forKey: "frame")

// retrieve
if let s = UserDefaults.standard.string(forKey: "frame") {
   let frame = CGRectFromString(s)
}

Upvotes: 56

Joe
Joe

Reputation: 57169

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);

Upvotes: 14

Related Questions