Question

I have an if statement in the App Delegate's application DidFinishLaunchingWithOptions. The code in the if statement runs even if the if statement isn't true. Am I doing something wrong? It just seems to be ignoring the if statement.

- (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;
}
Was it helpful?

Solution

You're storing this value into NSUserDefaults which doesn't get cleared when you rebuild the app. In order to reset this number you will have to uninstall the app from either the simulator or the device and rebuild.

The point of NSUserDefaults is that it is truly persistent. It will remain even if your application is updated from the app store, and the only two ways of clearing it's data are to specifically and deliberately remove the key you are referencing, or by deleting the app.

Additionally, as you can see below I've made a couple of slight tweaks for you:

- (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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top