aboodmanna aboodmanna - 1 year ago 95
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 Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download