开发者

Can this code be used with an array of custom objects?

开发者 https://www.devze.com 2023-01-16 22:22 出处:网络
[[NSUserDefaults standardUserDefaults] setObject:myArray forKey:@\"myArray\"]; If I make an array of custom objects conform to the NSCoding protocol, then does the above work? Do I have to make both
[[NSUserDefaults standardUserDefaults] setObject:myArray forKey:@"myArray"];

If I make an array of custom objects conform to the NSCoding protocol, then does the above work? Do I have to make both the custom class and the view controller that ho开发者_开发知识库lds the array of custom objects conform to the NSCoding protocol or just the custom class? Do I have to use NSKeyedArchiver somewhere?


It looks like you will need to archive your array, either with NSKeyedArchiver or NSArchiver. If you first archive the array into a NSData object:

NSData *data = [NSKeyedArchiver archivedDataWithRootObject:myArray];

You can then store that data in NSUserDefaults like so:

[[NSUserDefaults standardUserDefaults] setObject:data forKey:@"myArray"];

To load the array, use:

NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:@"myArray"];
NSArray *myArray = [NSKeyedUnarchiver unarchiveObjectWithData:data];

If you want to use an NSMutableArray then just replace any NSArray occurrences in the code above with NSMutableArray. OR you can just NSMutableArray *myMutableArray = [myArray mutableCopy] will give you a NSMutableArray to work with.

But then hey, if you are going to the trouble of making it NSCoding compliant, why not just archive it to a file?

The documentation that made me think that you will need to use an archiver is here so that you can check for yourself.

0

精彩评论

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