NSUserDefaults standardUserDefaults setObject: for

2019-05-29 08:03发布

问题:

I am trying to do following task

[[NSUserDefaults standardUserDefaults] setObject:@"Dry" forKey:@"vesselType_preference"];
[[NSUserDefaults standardUserDefaults] synchronize];

where my "vesselType_preference" is multivalue attribute, but it is not getting effected. Please help this is working for other type of attribute but not working for multivalue type.

Thanks

回答1:

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];        
    if (![defaults objectForKey:@"vesselType_preference"])
    {
        [defaults setObject:@"Dry" forKey:@"vesselType_preference"];
    }
    [[NSUserDefaults standardUserDefaults] synchronize];

This should work.



回答2:

NSUserDefaults can only handle objects of NSDictionary, NSData, NSArray, NSString and BOOL. (There might be another in there, not sure) If you need to store a multiple value object like an array or dictionary, I would store your settings there first, then save that to the defaults.

Your code looks fine for storing information to the user defaults. Just make sure you have your object type specified before saving. (id) will not work... or won't work properly.