问题描述:

I have this NSUserDefaults setup code

 NSDictionary *appDefaults = [NSDictionary

dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:@"DidBuyInAppPurchase"];

[[NSUserDefaults standardUserDefaults] registerDefaults:appDefaults];

I check later like so:

if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DidBuyInAppPurchase"] == YES){//some code}

Does this mean that a BOOL exists for the key or that the key was set to YES?

The odd behavior was that I wrote code in viewDidLoad that set the BOOL to YES just to test. Prior to doing this, the if-statement did not proceed. Now it does even when I remove the code that sets standardUserDefaults to YES is removed. Even if I remove the app and build and run on the device, the code proceeds.

This would indicate that the if check compares the YES to whether a boolean value exists there or not, and somehow the YES is persisting on app removal as well. However, the initial run of the app should have caught this too since a value existed. I checked this SO question and it seems that the if check should check for a YES value and not existence of a value.

This is for an IAP - when user purchases, the boolean is set to YES to show that it has been purchased, and if so, different viewControllers are presented to the user. How can I set this up properly so that setting to YES performs properly in if checks?

EDIT: Seems like this was in issue in Simulator on iOS 8 - the default not deleting from the Application domain. Not sure if this is the case here on the device in iOS 9 or I'm just using NSUserDefaults incorrectly.

网友答案:

When you use the -boolForKey: method, it internally does 2 things. First, it looks up an object for the key and second, it tries to unwrap a BOOL from an NSNumber object (returning that BOOL).

If that NSNumber is not present, the return will be "NO". If that NSNumber is present, the boolean the object is wrapping will be returned.

To check for the reason NSUserDefaults returned NO, you may call -objectForKey: with the same key and simply test the existence of an object.

网友答案:

Apple states, that the method you use to import predefined settings won't save anything, it just adds the dictionary's entries to the in-memory defaults. I have not seen your whole code on my small display... -registerDefaults:

相关阅读:
Top