NSUserDefaults - How to tell if a key exists

前端 未结 11 1810
耶瑟儿~
耶瑟儿~ 2020-12-12 11:06

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 som

11条回答
  •  一整个雨季
    2020-12-12 11:44

    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.

提交回复
热议问题