3 回答
TA贡献2011条经验 获得超2个赞
Marc和Chris所说的差不多,尽管我更喜欢在应用程序退出时更改其值,以防应用程序有多个领域需要了解它。在代码中:
目标C
// -applicationDidFinishLaunching:
[[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],@"firstLaunch",nil]];
// to check it:
[[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunch"];
// -applicationWillTerminate:
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"firstLaunch"];
斯威夫特5.0
// -applicationDidFinishLaunching:
UserDefaults.standard.register(defaults: ["firstLaunch":true])
// to check it:
UserDefaults.standard.bool(forKey: "firstLaunch")
// -applicationWillTerminate:
UserDefaults.standard.set(false, forKey: "firstLaunch")
TA贡献1725条经验 获得超7个赞
我意识到这个问题已经很老了,但是我用它提出了一种检测“全新安装”后首次启动的方法(相对于升级/降级之后的首次启动),并认为我将在此处共享代码将来的观众,以防万一。
// Get current version ("Bundle Version") from the default Info.plist file
NSString *currentVersion = (NSString*)[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];
NSArray *prevStartupVersions = [[NSUserDefaults standardUserDefaults] arrayForKey:@"prevStartupVersions"];
if (prevStartupVersions == nil)
{
// Starting up for first time with NO pre-existing installs (e.g., fresh
// install of some version)
[self firstStartAfterFreshInstall];
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObject:currentVersion] forKey:@"prevStartupVersions"];
}
else
{
if (![prevStartupVersions containsObject:currentVersion])
{
// 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.
[self firstStartAfterUpgradeDowngrade];
NSMutableArray *updatedPrevStartVersions = [NSMutableArray arrayWithArray:prevStartupVersions];
[updatedPrevStartVersions addObject:currentVersion];
[[NSUserDefaults standardUserDefaults] setObject:updatedPrevStartVersions forKey:@"prevStartupVersions"];
}
}
// Save changes to disk
[[NSUserDefaults standardUserDefaults] synchronize];
TA贡献1868条经验 获得超4个赞
这是一个非常简单的快捷方式,但是我发现第一次运行应用程序时,NSUserDefault键值对始终为NULL,因此
// Check to see if its the first time
if ([[NSUserDefaults standardUserDefaults] valueForKey:@"firstTime"] == NULL) {
[[NSUserDefaults standardUserDefaults] setValue:@"Not" forKey:@"firstTime"];
}
并将此代码放置在应用程序启动时显示的视图控制器的awakeFromNib中。我不知道是否有其他答案可以解决您的问题,但这就是我解决问题的方法。
- 3 回答
- 0 关注
- 645 浏览
添加回答
举报