NSUserDefaults BOOL logic

2019-09-17 16:09发布

I have a quiz game, where when the answer was correct, a picture with tick sign will appear. As I have many fields and need the app to remember which are done already for next launch. I am using NSUserDefaults. It is working great, but the problem is, that at the very first launch all "done" images are displayed. I was trying to get around the BOOL logic but no success.

.h

BOOL doneState;

.m

- (void)viewDidLoad{

    [super viewDidLoad];
    [self doneHidden];
    [self checkBools];
} 

- (void)checkBools{

    //--------NSUserDefaults & tick sign hidden
    BOOL saved = [[NSUserDefaults standardUserDefaults] boolForKey:@"hiddenDone"];
    NSLog (@"Value of my saved BOOL = %@", saved ? @"YES" : @"NO");
    done.hidden = saved;
}

-(void)doneHidden{
   done.hidden = YES;
}

When user quits the app, method below memorises the BOOL value

-(IBAction)flipBack:(id)sender{

    if (done.hidden == NO) {
        doneState = NO;
    }
    else {
        doneState = YES;
    }

    [[NSUserDefaults standardUserDefaults] setBool:doneState forKey:@"hiddenDone"];
    NSLog (@"Value of BOOL 1  = %@", doneState ? @"YES" : @"NO");
}

The idea is to first hide the imageView named "done" and then run through the BOOL. The console gives result on the very first launch that it is not hidden, even though It is set that way.

Console output:

Value of my saved BOOL = NO;

How can I improve the logic of it?

  • Hide image on very first launch
  • When quitting app check if image is visible and create BOOL
  • Next launch read the BOOL and display image if previously saved so

1条回答
Summer. ? 凉城
2楼-- · 2019-09-17 16:57

There are three options:

  1. Change the meaning of the BOOL to showImage so you set it to TRUE when you want to show the image.
  2. Pre-register a TRUE value for this key in -[NSUserDefaults registerDefaults:]
  3. Instead of using boolForKey:, use objectForKey: and first check if the object is nil (= not yet set), and only if non-nil, use -[NSNumber boolValue] to get the boolean value.
查看更多
登录 后发表回答