2014-03-31 96 views
3

我想在應用第一次啓動時只打開一次ViewController。以下是我的代碼。問題是當我寫入YES爲NSUserdefaults,進行同步,然後關閉應用程序。在使用模擬器的Xcode中,值不會更新爲是。無法保存NSUserDefaults值iOS

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"isFirstLaunch"]) 
    { 
     // app already launched 
     [[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:NO],@"isFirstLaunch", nil]]; 
     [[NSUserDefaults standardUserDefaults]synchronize]; 
    } 

    else 
    { 
     [[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],@"isFirstLaunch", nil]]; 
     [[NSUserDefaults standardUserDefaults]synchronize]; 
    } 

    return YES; 
} 

- (void)applicationDidBecomeActive:(UIApplication *)application 
{ 
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"isFirstLaunch"]) 
    { 
      NSLog(@"first time"); 
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil]; 
    LASplashUserSettingViewController *splash = [storyboard instantiateViewControllerWithIdentifier:@"splash"]; 
    [self.window.rootViewController presentViewController:splash animated:NO completion:nil];// 
    } 

} 

Why is NSUserDefaults not saving my values?

以上的有跟隨等多個環節。我在這裏錯過了什麼? 謝謝,

回答

2

我在這裏失蹤了什麼?

-registerDefaults:doesn't do what you think it does。改爲使用-setBool:forKey:

-registerDefaults:用於確保默認系統中某些鍵的值存在。在該方法之後無需調用-synchronize,因爲註冊域中的值永遠不會保存。您可能打算使用該方法爲isFirstLaunch設置默認值YES,但您的代碼在之前檢查了密鑰的值,您註冊了默認值!這違背了該方法的目的。正確使用將首先呼叫-registerDefaults:,然後檢查與該關鍵字相關聯的值,如果該值爲YES,則請致電-setBool:forKey:以保存值NO

檢測首次啓動的更簡單的選項是顛倒這個問題。完全跳過-registerDefaults:,並將密鑰更改爲appHasRunPreviously。如果沒有值存儲給定的密鑰,-boolForKey:將返回NO。如果發生這種情況,您知道這是該應用第一次運行,您應該使用-setBool:forKey:爲該密鑰保存YES

+1

該鏈接非常有用..謝謝Caleb .. – LUI

-2

你可以試試這個

[[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"AlreadyLaunched"]; 


[[NSUserDefaults standardUserDefaults]boolForKey:@"AlreadyLaunched"] 
0

這是你如何在AppDelegate.m NSUserDefaults的使用

+ (void)initialize 
{ 
    // Register defaults for first time 
    NSMutableDictionary *defs = [NSMutableDictionary dictionary]; 
    [defs setObject:[NSNumber numberWithBool:YES] forKey:@"isFirstLaunch"]; 
    [[NSUserDefaults standardUserDefaults] registerDefaults:defs]; 
} 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; 

    if([defaults boolForKey:@"isFirstLaunch"]) 
    { 
     // Do your stuff here 

     [defaults setBool:NO forKey:@"isFirstLaunch"]; 
     [defaults synchronize]; 
    } 
} 

不要設置isFirstLaunch回是在其他條件,如果你只希望視圖被顯示一次。