NSUserDefaults returns before it has been set

可紊 提交于 2019-12-11 04:54:11

问题


Im making an app that takes two strings and an int. I want these to be displayed on another view.

I have put them into an array and Im trying to store them in the NSUserDefaults. I have managed to get this data stored. The problem that im having is that when I change the data and save it again The function that gets the array is called before the one that sets it . So the application always displays the previous data.

I thought It would be easy to fix by changing when the functions are called.

but from the code it looks to me lie they are in the right order.

2012-09-26 13:55:02.764 BeerDivider[4377:907] array returnd = (
    2,
    "Person 1",
    "Person 2"
)
2012-09-26 13:55:02.773 BeerDivider[4377:907] array saved = (
    5,
    "Person 1",
    "Person 2"
)

I can see from logging the array that they are called in the wrong order.

Please can anyone see where im going wrong. This is my first objective-c/xcode post so not sure what code you want to see. I will put in all of it.

http://pastebin.com/BX5gqp17

Sorry if this is a lot of code.

Thanks for the help.

EDIT: update the code

EDIT2: I think what is happening is similar to this iOS do the button's action before prepareSegue


回答1:


First Take a look on Apple documentation of NSUserDefault
NSUserDefault always return the data which you saved in it

Dont forgot to write [defaults synchronize];

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:yourArray forKey:@"YourKey"]
    [defaults synchronize];

According to your given code.

-(void)saveInfo:(NSArray *)myArray
    {
         NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:myArray forKey:@"array"];
    [defaults synchronize];
    NSLog (@"array saved = %@", [defaults objectForKey:@"array"]);
    }  

and now check result




回答2:


Do this:

-(void)saveInfo:(NSArray *)myArray
{
    [[NSUserDefaults standardUserDefaults] setObject:myArray forKey:@"array"];
    [[NSUserDefaults standardUserDefaults] synchronize]; //u forgot this
    NSLog (@"array saved = %@", myArray);
}


来源:https://stackoverflow.com/questions/12602580/nsuserdefaults-returns-before-it-has-been-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!