当我NSLog它时,NSUserDefaults没有保存

时间:2013-09-20 13:16:28

标签: ios nsmutablearray nsuserdefaults nslog

我正在尝试将NSMutableArray数据保存到NSUserDefaults,但在我的日志中完成后仍然是(null)值。 我的代码有问题吗?

- (void)applicationDidEnterBackground:(UIApplication *)application
{
NSUserDefaults*defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:self.FlipsideView.myMutableArray forKey:@"NSMutableArray"];
[defaults synchronize];
NSLog(@"tableview data: %@", self.FlipsideView.myMutableArray);
NSLog(@"tableview data: %@", [defaults objectForKey:@"NSMutableArray"]);
}

这是我的调试结果:

2013-09-20 15:10:08.914 Milosova[4033:a0b] tableview data: (null)
2013-09-20 15:10:08.915 Milosova[4033:a0b] tableview data: (null)

这是来自我的ViewController的代码,我将一些数字放入textFields:

- (void)counter:(id)sender{

double value1 = [litre.text doubleValue];
double value2 = [kilometer.text doubleValue];
double result = (value1 / value2) * 100;
self.display.text = [NSString stringWithFormat:@"%.2lf", result];
function*newCell = [[function alloc] initWithName:self.litre.text done:NO];
[self.flipsideView.myMutableArray addObject:newCell];
newCell = [[function alloc] initWithName:self.kilometer.text done:NO];
[self.flipsideView.myMutableArray addObject:newCell];
newCell = [[function alloc] initWithName:self.display.text done:NO];
[self.flipsideView.myMutableArray addObject:newCell];
[self.flipsideView.tableView reloadData];
}

这是我的功能代码:

-(id)initWithName:(NSString *)name done:(BOOL)done{
self = [super init];

if (self) {
    self.name = _name;
    self.done = _done;
}
return self;
}

我通过prepareForsegue方法输入tableView:

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if ([segue.identifier isEqualToString:@"route"]) {
    UINavigationController *navi = segue.destinationViewController;
    MainViewController*controller = [navi.viewControllers objectAtIndex:0];
    controller.flipsideView = self;

} }

2 个答案:

答案 0 :(得分:0)

正如Desdenova指出的那样,你想要添加的数组是零,所以你添加到用户默认值的内容当然也是零。

您需要将有效的属性列表对象添加到用户默认值。 Nil对象或非属性列表对象的对象将不会保存。

如果你认为self.FlipsideView.myMutableArray应该是非零的,你需要追踪创建和填充该数组的代码。

如果声明属性为weak或unsafe_unretained,那么这就是你的问题。它正在被取消分配。

答案 1 :(得分:0)

您的代码中还缺少一个未进行同步的问题NSUserDefaults尝试使用下面的代码行

[[NSUserDefaults standardUserDefaults] synchronize];