我在NSMutableArray
中看到了一些关于如何根据NSUserDefaults
保存对象的帖子,但有一种方法可以使用[NSKeyedArchiver]
进行编码并对其进行编码与NSCoder
虽然我很难理解如何做,并希望有人可以提供帮助。
Student *student1 = [Student studentWithImage:[UIImage imageNamed:@"default"] withForename:@"John" withSurname:@"Smith" withAddress:@"3 Fake Road, Faketown, FA31 KEE" withDateOfBirth:[dateFormatter dateFromString:@"17-Jul-93"] withAge:24];
[studentArray addObject:student1];
我希望将此内容和其他一些类似的Students
保存到我的NSMutableArray
studentArray
。我想将此数组保存到NSUserDefaults
并重新加载它。
I have seen this post here看起来是我问题的正确答案,但我需要帮助将其实现到我的代码中,因为我很难理解它! 谢谢
答案 0 :(得分:3)
首先在Student
类
- (void)encodeWithCoder:(NSCoder *)coder;
{
[coder encodeObject:self.Forename forKey:@"keyForename"];
// do same for all property
}
- (id)initWithCoder:(NSCoder *)coder;
{
self = [[Student alloc] init];
if (self != nil)
{
self.Forename = [coder decodeObjectForKey:@"keyForename"];
// do same other property here
}
return self;
}
存储阵列
[studentArray addObject:student1];
[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:studentArray] 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];
}
}