开发者

Problems saving values in NSUserDefaults

I have this as my viewDidLoad:

- (void)viewDidLoad
{
    [super viewDidLoad];开发者_开发问答
    if (defaults == [cells objectAtIndex:0])
    {
        NSString * myFile = [[NSBundle mainBundle]pathForResource:@"cells" ofType:@"plist"];
        cells = [[NSMutableArray alloc]initWithContentsOfFile:myFile];
    }
    else
    {
        [defaults stringForKey:@"string1"];
    }
}

And for my viewWillDisappear I have:

-(void)viewWillDisappear:(BOOL)animated
{
    string1 = [cells objectAtIndex:0];
    [defaults setObject:string1 forKey:@"string1"];
}

But I cannot get the data to be saved. Does anyone know what I'm doing wrong?


defaults should be an instance of NSUserDefaults:

defaults = [NSUserDefaults sharedUserDefaults];

Therefore, if (defaults == [cells objectAtIndex:0]) is not a valid line of code and it will never be equal unless you're fiddling with the RAM.

Otherwise, the code looks fine.


Are you setting defaults to [NSUserDefaults standardUserDefaults] somewhere? Also, why are you comparing it to the first object in the cells array? Seems strange.

You've otherwise got the idea correct. Make sure the viewWillDisappear method is actually getting called. Also you can call [NSUserDefaults synchronize] to save the changes immediately.

One last thing, you aren't doing anything in that else {} block. You need to assign the value of [defaults stringForKey:@"string1"]; to a variable to use it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜