iOS 应用启动检测

iOS app Launch Detection

我正在尝试让我的应用程序在每 3 次启动时执行一些操作。

我想知道是否有比我在下面所做的更有效的方法...

NSUserDefaults *timesRan;
int launchCount;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    timesRan = [NSUserDefaults standardUserDefaults];
    launchCount = [timesRan integerForKey:@"hasRan"] + 1;
    [timesRan setInteger:launchCount forKey:@"hasRan"];
    [timesRan synchronize];



                    if(launchCount == 3) {
                       //Do something every 3rd launch
                    }

                    if(launchCount == 6) {
                        //Do something every 3rd launch
                    }


                    if(launchCount == 9) {
                        //Do something every 3rd launch
                    }

                    if(launchCount == 12) {
                        //Do something every 3rd launch
                    }

                    if(launchCount == 15) {
                        //Do something every 3rd launch
                    }

可能不是更好的解决方案,但仍然是更好的条件检查。

将您的 if 条件替换为

if (launchCount  == 3) // Use launchCount % 3 == 0 if not reseting counters
{
    launchCount = 0 //reset counter and synchronise.
    [timesRan setInteger:launchCount forKey:@"hasRan"];
    [timesRan synchronize];
    // Additional logic goes here to be done on third launch
}

您可能还想使用 applicationWillEnterForeground