Pergunta

I have an iPad app where the user can set the idleTimerDisabled to YES or NO via a switch in preferences. That part works fine. However, initially setting it to YES in the app delegate's didFinishLaunchingWithOptions method if it's the first time the app has run doesn't work (the device auto-sleeps anyway).

I've tried the hack of setting it to NO first, then to YES, as described in other threads to no avail. All other aspects of the preferences (standardUserDefaults) are working fine, as well.

Here's the relevant code:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 
    // if app run for the first time, set these as defaults
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    if (![prefs objectForKey:@"autoSleep"]) {
    // this conditional code runs, as traced using NSLog   
    [prefs setBool:YES forKey:@"autoSleep"];
    application.idleTimerDisabled = NO;
    application.idleTimerDisabled = YES;
    }
}
Foi útil?

Solução

Use the registerDefaults method of NSUserDefaults instead of testing if objectForKey is nil.

See also details about this in the relevant Programming Guide. Once you have register default values using registerDefaults (in your case the value NO for your "autoSleep" key), you are ensured that you will have a value in this key, either the one set in the application's settings by the user… or this default one if the user hasn't set a value for it yet.

Thus it should solve your problem as you will always have a value for your autoSleep key, either the default one or the user-provided one.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top