2

I am trying to save my NSMutableArray data into NSUserDefaults, but after it is done in my Log is still (null) value. Is something wrong with my code?

- (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"]);
}

and here is my debug result:

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)

here is code from my ViewController where i put some numbers into 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];
}

and this is my function code:

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

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

i put in into tableView via prepareForsegue method:

-(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;

} }
4

2 回答 2

0

您的代码中缺少另一件事,您没有同步NSUserDefaults尝试使用下面的代码行

[[NSUserDefaults standardUserDefaults] synchronize];
于 2013-09-21T11:11:25.143 回答
0

正如 Desdenova 指出的那样,您尝试添加的数组是 nil,因此您添加到用户默认值的内容当然也将是 nil。

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

如果您认为 self.FlipsideView.myMutableArray 不应该为 nil,则需要跟踪创建和填充该数组的代码。

如果该属性被声明为 weak 或 unsafe_unretained 那是你的问题。它正在被释放。

于 2013-09-20T14:38:34.870 回答