How do I save a custom struct
to NSUserDefaults
?
struct Paging {
NSInteger currentPage;
NSInteger totalResults;
NSInteger resultsPerPage;
};
typedef struct Paging Paging;
NSUserDefaults *userInfo = [NSUserDefaults standardUserDefaults];
[userInfo setStruct:paging forKey:@"paging"];
[userInfo synchronize];
The above code produces a run-time warning:
*** -[NSUserDefaults setObject:forKey:]: Attempt to insert non-property value...
I made the less favourable decision to use struct in my iOS app. Now I am also facing this problem where I cannot save the struct (which contains about 30 variables) into NSUserDefaults easily.
After trying many solutions given in SO and other sites, it has not working well for me. So finally I decided to create a simple method to convert the struct into NSMutableDictionary.
StructPictures is the name of my struct (custom). Hope this give an alternative solution to saving struct into NSUserDefaults.
One way is to turn it into NSData
In this case your struct is pretty simple, so you might want to add a category to NSUserDefaults to save and restore it. I'd implement that by saving an NSDictionary with four NSNumbers. A bit more work, but it means your plist will be humanly readable.
In your specific case, you can get away with using an
NSData
since the members are justint
s, but for future readers of this question, please read the Apple docs on Encoding and Decoding C Data Types before doing this!Encoding and Decoding C Data Types - Structures and Bit Fields:
That doc does say how to properly do it (but no examples are given unfortunately - when I come up with one however, I will update this answer with the example):
A method that is very similar to
NSData
wrapping but usesNSValue
(this is also discouraged, but will work for basic structs as well):NSValue
Documentation