您的位置:首页 > 移动开发 > Objective-C

保存自定义对象的数组 save and restore an array of custom objects

2014-11-02 17:54 786 查看
参考如下:

http://stackoverflow.com/questions/3648558/save-and-restore-an-array-of-custom-objects

http://www.crifan.com/store_save_array_of_custom_object_class_into_nsuserdefaults_in_iphone_ios/comment-page-1/

http://stackoverflow.com/questions/2315948/how-to-store-custom-objects-in-nsuserdefaults

使用NSUserDefaults

归档array,使用如下方法:

[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:myArray] forKey:@"mySavedArray"];


使用如下的代码,加载自定义的对象
NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
NSData *savedArray = [currentDefaults objectForKey:@"mySavedArray"];
if (savedArray != nil)
{
NSArray *oldArray = [NSKeyedUnarchiver unarchiveObjectWithData:savedArray];
if (oldArray != nil) {
customObjectArray = [[NSMutableArray alloc] initWithArray:oldArray];
} else {
customObjectArray = [[NSMutableArray alloc] init];
}
}


自定义的对象必须实现NSCoder协议,如下:
- (void)encodeWithCoder:(NSCoder *)coder;
{
[coder encodeObject:aLabel forKey:@"label"];
[coder encodeInteger:aNumberID forKey:@"numberID"];
}

- (id)initWithCoder:(NSCoder *)coder;
{
self = [[CustomObject alloc] init];
if (self != nil)
{
aLabel = [coder decodeObjectForKey:@"label"];
aNumberID = [coder decodeIntegerForKey:@"numberID"];
}
return self;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐