0

我在 App Delegate 的application DidFinishLaunchingWithOptions. 即使 if 语句不正确,if 语句中的代码也会运行。难道我做错了什么?它似乎只是忽略了 if 语句。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{ 
NSInteger i = [[NSUserDefaults standardUserDefaults] integerForKey:@"numOfLCalls"];
[[NSUserDefaults standardUserDefaults] setInteger:i+1 forKey:@"numOfLCalls"];

if (i >= 3) {
    UIAlertView *alert_View = [[UIAlertView alloc] initWithTitle:@"Hey! You are still coming back!" message:@"It would mean a whole lot to me if you rated this app!" delegate:self cancelButtonTitle:@"Maybe later" otherButtonTitles: @"Rate", nil];
    [alert_View show];
}

self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
4

1 回答 1

2

您存储的这个值NSUserDefaults在您重建应用程序时不会被清除。为了重置这个数字,您必须从模拟器或设备上卸载应用程序并重新构建。

关键NSUserDefaults是它是真正持久的。即使您的应用程序是从应用商店更新的,它仍会保留,并且清除其数据的唯一两种方法是专门和故意删除您正在引用的密钥,或删除应用程序。

此外,正如您在下面看到的,我为您做了一些细微的调整:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    if (![[NSUserDefaults standardUserDefaults] integerForKey:@"numOfLCalls"]) {
        [[NSUserDefaults standardUserDefaults] setInteger:1 forKey:@"numOfLCalls"];
    }else{
        NSInteger i = [[NSUserDefaults standardUserDefaults] integerForKey:@"numOfLCalls"];
        [[NSUserDefaults standardUserDefaults] setInteger:i++ forKey:@"numOfLCalls"];
    }

    if (i >= 3) {
        UIAlertView *alert_View = [[UIAlertView alloc] initWithTitle:@"Hey! You are still coming back!" message:@"It would mean a whole lot to me if you rated this app!" delegate:self cancelButtonTitle:@"Maybe later" otherButtonTitles: @"Rate", nil];
        [alert_View show];
    }

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
    return YES;
}
于 2012-09-04T01:38:15.437 回答