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.
It appears the limit is the maximum file size for iOS (logically), which is currently 4GB: https://discussions.apple.com/thread/1763096?tstart=0. The precise size of the data is circumscribed by the compiler types (NSData, NSString, etc.) or the files in your asset bundle.
The user's defaults database is stored on disk as a property list or plist. A property list or plist is an XML file. At runtime, the UserDefaults class keeps the contents of the property list in memory to improve performance. Changes are made synchronously within the process of your application.
Storing Default Objects The NSUserDefaults class provides convenience methods for accessing common types such as floats, doubles, integers, Boolean values, and URLs.
You can save your mutable array like this: [[NSUserDefaults standardUserDefaults] setObject:yourArray forKey:@"YourKey"]; [[NSUserDefaults standardUserDefaults] synchronize]; Later you get the mutable array back from user defaults. It is important that you get the mutable copy if you want to edit the array later.
Here is a much simpler solution, using NSString
:
// store:
[[NSUserDefaults standardUserDefaults]
setValue:NSStringFromCGRect(frame) forKey:@"frame"];
// retrieve:
CGRect frame = CGRectFromString(
[[NSUserDefaults standardUserDefaults] stringForKey:@"frame"]);
// 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With