aboodmanna aboodmanna - 4 months ago 24
iOS Question

Objective C - Saving a variable inside NSUserDefaults

I have a class called "EntityType" that has a string "name" and I am using NSUserDefaults to save it so I tried this:

if (button.selected)
{
[button setSelected:YES];
[[NSUserDefaults standardUserDefaults]setObject:[NSNumber numberWithBool:YES] forKey:@"buttonSelected"];
}


I want to access the variable from another class and save it inside NSUserDefaults

Answer

You have missed sync call.Apply this to save it.

if (button.selected)
{
    [button setSelected:YES];
    [[NSUserDefaults standardUserDefaults]setObject:[NSNumber numberWithBool:YES] forKey:@"buttonSelected"];
     [[NSUserDefaults standardUserDefaults] synchronize];

}

to get it back later

NSNumber* savedValue = [[NSUserDefaults standardUserDefaults]
    objectForKey:@"buttonSelected"];

This is if you want to store only the value. If you want to store your custom object look at this link How to store custom objects in NSUserDefaults