jeudi 4 juin 2015

Objective-C: If statement only runs after second attempt (iOS)

I've created an if statement that checks whether a bool is set to true or false

-(void) buttonClicked {

    if (sortedList) {       

        // code

        sortedList = NO;
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"sorted"];
    }

    else {

        // code

        sortedList = YES;
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"sorted"];
    }
}

The bool is loaded in viewWillAppear

    sortedList = [[NSUserDefaults standardUserDefaults] boolForKey:@"sorted"];

The problem is that when I click the button that calls buttonClicked, nothing happens. When I click it the second time, the correct code gets executed as expected (running the if or else correctly dependend on how it is set). The third, fourth etc. time the button is tapped, the code executes as expected. However, when I return to the view after another view has been displayed, the problem arrises again with no action on the first click only.

I've checked whether the bool is set at all in viewWillAppear using a log, but it appears to be set correctly (with the value I expect it to hold).

Does anyone have an idea what I am missing here?

EDIT: the buttonClicked method gets called as follows

[listButton addTarget:self action:@selector(buttonClicked) forControlEvents:UIControlEventTouchUpInside];

Aucun commentaire:

Enregistrer un commentaire