What is the best way to back up an NSMutableArray on NSUserDefaults?

综合技术 2017-11-15

I have a custom object called Occasion defined as follows:


@interface Occasion : NSObject {

NSString *_title;
NSDate *_date;
NSString *_imagePath;    


@property (nonatomic, retain) NSString *title;
@property (nonatomic, retain) NSDate *date;
@property (nonatomic, retain) NSString *imagePath;

Now I have an NSMutableArray of Occasions which I want to save to NSUserDefaults. I know it's not possible in a straight forward fashion so I'm wondering which is the easiest way to do that? If serialization is the answer, then how? Because I read the docs but couldn't understand the way it works fully.

You should use something like NSKeyedArchiver
to serialize the array to an NSData
, save it to the NSUserDefaults
and then use NSKeyedUnarchiver
to deserialize it later:

NSData *serialized = [NSKeyedArchiver archivedDataWithRootObject:myArray];
[[NSUserDefaults standardUserDefaults] setObject:serialized forKey:@"myKey"];


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

You will need to implement the NSCoding
protocol in your Occasion
class and correctly save the various properties to make this work correctly. For more information see the Archives and Serializations Programming Guide
. It shouldn't be more than a few lines of code to do this. Something like:

- (void)encodeWithCoder:(NSCoder *)coder {
    [super encodeWithCoder:coder];

    [coder encodeObject:_title forKey:@"_title"];
    [coder encodeObject:_date forKey:@"_date"];
    [coder encodeObject:_imagePath forKey:@"_imagePath"];

- (id)initWithCoder:(NSCoder *)coder {
    self = [super initWithCoder:coder];

    _title = [[coder decodeObjectForKey:@"_title"] retain];
    _date = [[coder decodeObjectForKey:@"_date"] retain];
    _imagePath = [[coder decodeObjectForKey:@"_imagePath"] retain];

    return self;
Hello, buddy!

责编内容by:Hello, buddy! (源链)。感谢您的支持!


UITableViewController in UISplitViewController I'm trying to load a specific UITableViewController as the Detail view of a ...
iOS 消息转发机制Demo解析 原文链接 :原文 假设说我们声明一个类, 初始化对象, 并且在此类声明一个方法, 调用方法的时候底层是怎么处理的呢? 今天我们来简单模拟测试, 来看道理发生了...
FMDB | 实现数据的增删改查 FMDB 是一个轻量级的数据库,用于将网络资源存储在本地。 项目中使用 ARC 还是 MRC,对使用 FMDB 都没有任何影响,FMDB 会在编译项目时自动匹...
Understanding the Kentico Cloud iOS SDK We know that Apple’s iOS is still currently the standout mobile operating system...
用JSONExport一键生成Model 以前跟着《第一行代码》入门 Android 的时候,学过几个解析 json 的方法,一个一个按 key 名找、建对象存等等,解析的工具也很多,以前对 json ...