質問

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;

} }
役に立ちましたか?

解決

As Desdenova pointed out, the array you are trying to add is nil, so of course the content you add to user defaults will also be nil.

You need to add a valid property list object to user defaults. Nil objects, or objects that are not property list objects will not save.

If you think self.FlipsideView.myMutableArray should be non-nil, you need to go trace through the code that creates and populates that array.

If the property is declared as weak or unsafe_unretained that is your problem. It's getting deallocated.

他のヒント

One more thing is missing in your code you are not synchronizing NSUserDefaults try to use below lines of code

[[NSUserDefaults standardUserDefaults] synchronize];
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top