문제

I have a settings bundle with a single item in it. The item is a switch that is set to NO.

I am using this to allow the user to sign out of the application I would like to make. However when the user opens the app then goes to settings and selects the switch to log out when they go back into the application nothing happens. If they go back out to the settings switch it again then go back in then the if statement is entered correctly.

It is almost like the settings are not read the first time but I am not sure how to fix this.

This is what my code looks like:

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    NSUserDefaults *settings = [NSUserDefaults standardUserDefaults];
    NSNumber *branchString = [settings objectForKey:@"signout"];

    NSLog(@"%@", branchString);

    if ((branchString != nil) || (branchString != 0)) {      
        // turn signout back on.
        [settings setObject:NO forKey:@"signout"];
        [settings synchronize];
    }
}
도움이 되었습니까?

해결책

User defaults acts like other container classes: they take objects as elements not scalar types. So you need to wrap that scalar type (BOOL) with an NSNumber:

[settings setObject:[NSNumber numberWithBool:NO] forKey:@"signout"];
// with modern syntax
[settings setObject:@(NO) forKey:@"signout"];

But it sounds like you're getting the value from a switch, so you won't be able to use the new literal syntax, that is:

[settings setObject:[NSNumber numberWithBool:self.mySwitch.on] forKey:@"signout"];

Remember, when reading back from defaults, you'll need to unwrap the wrapped scaler, like this:

self.mySwitch.on = [[settings objectForKey:@"signout"] boolValue];

다른 팁

Your posted code is confusing. The 1st time the app is run (and the user has not yet gone to settings and changed the switch), branchString will be nil which should be treated as NO.

Your code should be something like this:

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    NSUserDefaults *settings = [NSUserDefaults standardUserDefaults];
    BOOL signout = [settings boolForKey:@"signout"];

    NSLog(@"%d", signout); // will be 0 (NO) or 1 (YES)

    if (signout) {      
        // The user has changed the switch to on
        // turn signout back off.
        [settings setBool:NO forKey:@"signout"];
        [settings synchronize];
    } else {
        // The user has either changed the switch to off or it is still off by default
    }
}

Your original if statement makes no sense since it will be true once the user changes the switch to on and then after that it will be true even if they turn the switch off again.

Side note - why do you make the user switch out to the Settings app just so they can log out? Why not give the ability to sign out right in your app? That would be a much better user experience.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top