开发者

Saving NSRect to NSUserDefaults

开发者 https://www.devze.com 2023-04-12 10:42 出处:网络
Currently I\'m trying to save an NSRect to my user defaults.Right now I\'m using a NSValue to wrap it as an object then save it into the user defaults as an object with the following code

Currently I'm trying to save an NSRect to my user defaults. Right now I'm using a 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? Thanks.


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


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

精彩评论

暂无评论...
验证码 换一张
取 消