2012-09-21 24 views
1

我有一个故事板和导航控制器的应用程序,我想如果用户启动应用程序第一时间弹出一个协议视图,在Appdelegate.m反向问号布尔值NSUserDefaults的IOS

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
    //app launched first time 
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults]; 
    [prefs setBool:YES forKey:@"firstTime"]; 
    BOOL firstTime = [prefs boolForKey:@"firstTime"]; 
    NSLog(@"firstTime %c",firstTime); 

    //check if user has agreed agreement or not 
    if (firstTime==YES) { 

     //replace and push rootview manually 
     UIStoryboard *storyboard = [UIApplication sharedApplication].delegate.window.rootViewController.storyboard; 

     UIViewController *loginController = [storyboard instantiateViewControllerWithIdentifier:@"AgreementViewController"]; 

     [self.window.rootViewController presentModalViewController:loginController animated:YES]; 

    return NO; 
    }else 

    return YES; 
} 

Nslog了我第一次拿到reverse question mark sign,我想这既不设置为yes或no

所以,我怎么能设置一个布尔值,它保存在iOS设备,并调用它每次应用程序启动?

回答

3

您需要使用方法NSUserDefaults的,registerDefaults。该方法允许您为默认值设置一个值(您的情况为YES),仅当用户未更改该值时才使用该值。一旦用户将该值更改为NO,注册的默认值将不再有任何效果。

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults]; 
[prefs registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],@"firstTime", nil]; 
BOOL firstTime = [prefs boolForKey:@"firstTime"]; 
//check if user has agreed agreement or not 
if (firstTime==YES) { ..... 

然后,后来的某个地方,当用户做你想要什么,你会设置键的值,“firstTime”,都没有按照通常的方式。