我正在尝试在应用关闭时保存NSMutableArray,然后在启动时将其加载到tableview。
这是我的代码:
- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:_savedText forKey:@"savedText"];
}
- (id)initWithCoder:(NSCoder *)decoder {
if((self = [super initWithCoder:decoder])) {
_savedText = [decoder decodeObjectForKey:@"savedText"];
}
return self;
}
我使用此代码保存MutableArray:
- (void)applicationDidEnterBackground:(UIApplication *)application {
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:_savedText];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:@"savedText"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
然后加载它:
- (void)viewDidLoad {
NSData *savedData = [[NSUserDefaults standardUserDefaults] objectForKey:@"savedText"];
NSMutableArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:savedData];
array = [_savedText copy];
}
没有错误,但启动时表视图为空。我忘记了什么吗?
答案 0 :(得分:0)
您应该从默认值中读取数据并设置为_savedText对象。您正在将数据读入名为array
的var,然后分配array = [_savedText copy]
。这可能是零。应该是相反的。
- (void)viewDidLoad {
NSData *savedData = [[NSUserDefaults standardUserDefaults] objectForKey:@"savedText"];
NSMutableArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:savedData];
_savedText = [array copy];
}