我有什么方法可以只运行一次功能(当应用程序更新或安装时)?我不能使用运行脚本,因为我应该使用目标c函数。
答案 0 :(得分:44)
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
if ( ![userDefaults valueForKey:@"version"] )
{
// CALL your Function;
// Adding version number to NSUserDefaults for first version:
[userDefaults setFloat:[[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] floatValue] forKey:@"version"];
}
if ([[NSUserDefaults standardUserDefaults] floatForKey:@"version"] == [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] floatValue] )
{
/// Same Version so dont run the function
}
else
{
// Call Your Function;
// Update version number to NSUserDefaults for other versions:
[userDefaults setFloat:[[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] floatValue] forKey:@"version"];
}
答案 1 :(得分:7)
let infoDictionary: NSDictionary? = NSBundle.mainBundle().infoDictionary // Fetch info.plist as a Dictionary
let temp: NSString = infoDictionary?.objectForKey("CFBundleVersion") as NSString
let val: Float = temp.floatValue
var userDefaults = NSUserDefaults()
if userDefaults.valueForKey("version") == nil {
// Call function
// Adding version number to NSUserDefaults for first version
userDefaults.setFloat(val, forKey: "version")
}
if NSUserDefaults().floatForKey("version") == val {
// Same Version so dont run the function
} else {
// Call function
// Update version number to NSUserDefaults for other versions
userDefaults.setFloat(val, forKey: "version")
}
答案 2 :(得分:3)
如果您想在首次安装应用程序时或每次更新后运行一些代码,那么您可以从捆绑包中读取当前版本的应用程序
CGFloat currentVersion = [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] floatValue];
并在运行代码后将其写入用户默认值。
[[NSUserDefaults standardUserDefaults] setFloat:currentVersion
forKey:kLastVersionThatExecutedMyCodeKey];
下次启动应用时,会将用户默认值与包版本进行比较。如果捆绑版本已更改,则应用程序已更新,这意味着您应该再次运行代码并将新版本写入用户默认值。
答案 3 :(得分:2)
您可以在isFirstLaunch = NO
中创建BOOL值键(例如NSUserDefaults
),并在执行该功能后将其设置为YES。
如果您想在每次用户启动App时执行它,您需要在应用程序存在之前将密钥设置为默认值(即在AppDelegate中的-applicationWillTerminate:
方法中重置它)。
答案 4 :(得分:1)
如果有人需要,这是Bhupendra的答案的Swift2.0版本!
let infoDictionary: NSDictionary? = NSBundle.mainBundle().infoDictionary
//Fetch info.plist as a Dictionary
let temp: NSString = infoDictionary?.objectForKey("CFBundleVersion") as! NSString
let val: Float = temp.floatValue
let userDefaults = NSUserDefaults()
if userDefaults.valueForKey("version") == nil {
userDefaults.setFloat(val, forKey: "version")
}
if NSUserDefaults().floatForKey("version") == val {
//if it is the same version, don't run the code
}
else {
userDefaults.setFloat(val, forKey: "version")
}
}