ChatGPT解决这个技术问题 Extra ChatGPT

NSUserDefaults - How to tell if a key exists

I'm working on a small iPhone app, and I am using NSUserDefaults as my data persistence. It only has to keep track of a few things, such as some names and some numbers so I figure I might as well keep it simple.

I found this page for some reference, but I don't think it can answer my question. Basically, I want to be able to check if a value (or a key) already exists in the NSUserDefaults and then do something accordingly.

Some examples: The app starts up, if this is the first time it starts up it outputs an alert saying welcome. To tell if this is first time it has opened it reads the UserDefaults and checks.

Example 2: It says, "Hello [Name]", where Name is something you have entered. If you have opened the app and there is no name, it should say "Hello World." I need to check if you have entered a name already and act accordingly. The name would be stored in NSUserDefaults.

Some help here? I'd really appreciate it!


d
dreamlax

objectForKey: will return nil if it doesn't exist.


Apple's docs say that "If a boolean value is associated with defaultName in the user defaults, that value is returned. Otherwise, NO is returned." I don't think the above answer is correct for BOOLs, you can't determine if it's defined NO or doesn't exist. I think you'd have to use – dictionaryRepresentation and check for the key.
@zekel Rather than guessing, I tested this (on iOS 5.1.1), and it definitely detected whether or not a BOOL was present, independent of what the value of said BOOL might be. "objectForKey" returned nil when the BOOL was not present because it had never been set.
I third the notion, I just tested this and it can tell if the object exists, even if it's a BOOL set to NO.
If you have a BOOL and test it with boolForKey, then @zekel is right, you get YES or NOT. If you test it with objectForKey (as the answer suggests) you get nil if the key is not set.
This no longer works at least as of iOS 6.1 Simulator. objectForKey returns the same value if it's not present and if it is present with a BOOL of NO. i.jameelkhan's solution does work
i
i.jameelkhan

As mentioned above it wont work for primitive types where 0/NO could be a valid value. I am using this code.

NSUserDefaults *defaults= [NSUserDefaults standardUserDefaults];
if([[[defaults dictionaryRepresentation] allKeys] containsObject:@"mykey"]){

    NSLog(@"mykey found");
}

This saved me. Thanks!
This is the correct answer when dealing with primitives like BOOL. It will accurately distinguish between NO and not set, unlike objectForKey:.
@devios1 - If the key is missing, objectForKey: will return nil regardless of the programmer's intent to eventually store a Bool or any other data type. When a primitive is present, objectForKey: does not return nil even if the key is associated with a primitive value.
This is the right answer : obviously, the accepted answer is wrong since objectForKey confuses 0 with nil, so it can't work. Tested successfully from iOS 4.3 to 10.2.1
This is the slowest, and most cumbersome way to do this. you convert a whole .plist structure into an NSDictionary, just to find a single key? better use the NSUserDefaults controller standard machinery.
d
dreamlax

The objectForKey: method will return nil if the value does not exist. Here's a simple IF / THEN test that will tell you if the value is nil:

if([[NSUserDefaults standardUserDefaults] objectForKey:@"YOUR_KEY"] != nil) {
    ...
}

s
stef

Swift 3 / 4:

Here is a simple extension for Int/Double/Float/Bool key-value types that mimic the Optional-return behavior of the other types accessed through UserDefaults.

(Edit Aug 30 2018: Updated with more efficient syntax from Leo's suggestion.)

extension UserDefaults {
    /// Convenience method to wrap the built-in .integer(forKey:) method in an optional returning nil if the key doesn't exist.
    func integerOptional(forKey: String) -> Int? {
        return self.object(forKey: forKey) as? Int
    }
    /// Convenience method to wrap the built-in .double(forKey:) method in an optional returning nil if the key doesn't exist.
    func doubleOptional(forKey: String) -> Double? {
        return self.object(forKey: forKey) as? Double
    }
    /// Convenience method to wrap the built-in .float(forKey:) method in an optional returning nil if the key doesn't exist.
    func floatOptional(forKey: String) -> Float? {
        return self.object(forKey: forKey) as? Float
    }
    /// Convenience method to wrap the built-in .bool(forKey:) method in an optional returning nil if the key doesn't exist.
    func boolOptional(forKey: String) -> Bool? {
        return self.object(forKey: forKey) as? Bool
    }
}

They are now more consistent alongside the other built-in get methods (string, data, etc.). Just use the get methods in place of the old ones.

let AppDefaults = UserDefaults.standard

// assuming the key "Test" does not exist...

// old:
print(AppDefaults.integer(forKey: "Test")) // == 0
// new:
print(AppDefaults.integerOptional(forKey: "Test")) // == nil

I would prefer return self.object(forKey: key) as? Int in order to search value only once.
I guess it would be much better with generics" :)
J
JamesKVL

"objectForKey will return nil if it doesn't exist." It will also return nil if it does exist and it is either an integer or a boolean with a value of zero (i.e. FALSE or NO for the boolean).

I've tested this in the simulator for both 5.1 and 6.1. This means that you cannot really test for either integers or booleans having been set by asking for "the object". You can get away with this for integers if you don't mind treating "not set" as if it were "set to zero".

The people who already tested this appear to have been fooled by the false negative aspect, i.e. testing this by seeing if objectForKey returns nil when you know the key hasn't been set but failing to notice that it also returns nil if the key has been set but has been set to NO.

For my own problem, that sent me here, I just ended up changing the semantics of my boolean so that my desired default was in congruence with the value being set to NO. If that's not an option, you'll need to store as something other than a boolean and make sure that you can tell the difference between YES, NO, and "not set."


I've confirmed this, but there is an easy solution; just use the new object literals or a boxed expression. @0 instead of 0, @NO instead of NO, or simply @(variable). Read about them here.
A bit late, but for the benefit of newbies: this is incorrect. object(forKey) on UserDefault values of integers set to 0, and Bools set to false, will correctly return non-nil. If you use bool(forKey) to test if a value is set you can run into problems (because if the value is set to False, bool(forKey) will return 'false', even though you are expecting 'true'.)
m
mbelsky

Extend UserDefaults once to don't copy-paste this solution:

extension UserDefaults {

    func hasValue(forKey key: String) -> Bool {
        return nil != object(forKey: key)
    }
}

// Example
UserDefaults.standard.hasValue(forKey: "username")

j
james Burns

I just went through this, and all of your answers helped me toward a good solution, for me. I resisted going the route suggested by, just because I found it hard to read and comprehend.

Here's what I did. I had a BOOL being carried around in a variable called "_talkative".

When I set my default (NSUserDefaults) object, I set it as an object, as I could then test to see if it was nil:

//converting BOOL to an object so we can check on nil
[defaults setObject:@(_talkative) forKey:@"talkative"];

Then when I went to see if it existed, I used:

if ([defaults objectForKey:@"talkative"]!=nil )
  {

Then I used the object as a BOOL:

if ([defaults boolForKey:@"talkative"]) {
 ...

This seems to work in my case. It just made more visual sense to me.


This worked for me ([defaults boolForKey:@"talkative"]
p
pepelkod

Try this little crumpet:

-(void)saveUserSettings{
NSNumber*   value;

value = [NSNumber numberWithFloat:self.sensativity];
[[NSUserDefaults standardUserDefaults] setObject:value forKey:@"sensativity"];
}
-(void)loadUserSettings{
    NSNumber*   value;
    value = [[NSUserDefaults standardUserDefaults] objectForKey:@"sensativity"];
    if(value == nil){
        self.sensativity = 4.0;
    }else{
        self.sensativity = [value floatValue];
    }
}

Treat everything as an object. Seems to work for me.


B
Ben

Swift version to get Bool?

NSUserDefaults.standardUserDefaults().objectForKey(DefaultsIsGiver) as? Bool

Why not use boolForKey? NSUserDefaults.standardUserDefaults().boolForKey(DefaultsIsGiver)
boolForKey will return Bool and not Bool? , so if the key is not there you will get false and not nil
N
Nikhil Manapure

In Swift3, I have used in this way

var hasAddedGeofencesAtleastOnce: Bool {
    get {
        return UserDefaults.standard.object(forKey: "hasAddedGeofencesAtleastOnce") != nil
    }
}

The answer is great if you are to use that multiple times.

I hope it helps :)


K
Kiran Jasvanee

Swift 3.0

if NSUserDefaults.standardUserDefaults().dictionaryRepresentation().contains({ $0.0 == "Your_Comparison_Key" }){
                    result = NSUserDefaults.standardUserDefaults().objectForKey(self.ticketDetail.ticket_id) as! String
                }