我有一个NSArray的自定义对象,我想保存和恢复.这可以用NSUserDefaults来完成吗?
解决方法
如果将阵列存档到NSData中,仍然可以使用
NSUserDefaults.
对于存储阵列,可以使用以下代码:
[[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 *)编码器和 – (id)initWithCoder:(NSCoder *)编码器方法.
编辑.
下面是一个例子,您可以在 – (void)encodeWithCoder:(NSCoder *)编码器和 – (id)initWithCoder:(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; }