如何检查应用程序是否第一次启动?

时间:2012-02-15 18:32:14

标签: objective-c cocoa-touch

我正在开发一个新版本的应用。在旧版本的应用程序中,某些内容已从Web下载到Cache-folder中。此内容在新版本中不再有效,因此我想在新版本的应用程序启动时首次删除其中一些文件。

如何检查该应用是否首次启动?我可以使用NSUserDefaults存储指示,但是有更好的方法吗?

2 个答案:

答案 0 :(得分:5)

我所做的是检查应用程序是否首次在didFinishLaunchingWithOptions:方法中启动,并将当前版本的应用程序存储在默认值中。 这样做的原因是每次更新应用程序时,我都可以跟踪需要删除哪些文件,以及需要为该版本的应用程序存储哪些文件。 以下是代码:

if (![[NSUserDefaults standardUserDefaults] boolForKey:kNOT_FIRST_LAUNCH]) {
    NSLog(@"fresh install = %d", (int)[self checkForFreshInstall]);
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kAPPLICATION_LAUNCHING_FIRST_TIME];
    [[NSUserDefaults standardUserDefaults] synchronize];
} else {
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:kAPPLICATION_LAUNCHING_FIRST_TIME];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

这是checkForFreshIntallMethod:

- (BOOL) checkForFreshInstall {
NSString *currentVersion = (NSString*)[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];
NSString *prevVersion = (NSString *)[[NSUserDefaults standardUserDefaults] valueForKey:@"prevVersion"];

if (prevVersion == nil) {
    // Starting up for first time with NO pre-existing installs (e.g., fresh 
    // install of some version)
    [[NSUserDefaults standardUserDefaults] setValue:currentVersion forKey:@"prevVersion"];
    // Save changes to disk
    [[NSUserDefaults standardUserDefaults] synchronize];
    return YES;
}
else if ([prevVersion intValue] < [currentVersion intValue]) {
    // Starting up for first time with this version of the app. This
    // means a different version of the app was alread installed once 
    // and started.
    [[NSUserDefaults standardUserDefaults] setValue:currentVersion forKey:@"prevVersion"];
    // Save changes to disk
    [[NSUserDefaults standardUserDefaults] synchronize];
    return NO;
}
return YES;

}

如果您有任何问题,请与我们联系。

答案 1 :(得分:0)

NSUserDefaults方法没有任何问题。

if(the flag has not been set somewhere to say we've already done this dance){
 do the stuff we need to do 
 set the flag that we'll check again next time and skip this code next time
}
相关问题