更新应用程序时替换预加载的数据-iOS Swift
我有一个应用程序,在第一次启动时将CSV文件预加载到核心数据中,如下所示:更新应用程序时替换预加载的数据-iOS Swift,ios,core-data,nsuserdefaults,preload,Ios,Core Data,Nsuserdefaults,Preload,我有一个应用程序,在第一次启动时将CSV文件预加载到核心数据中,如下所示: func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { let isPreloaded = defaults.bool(forKey: "isPreloaded") if !
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let isPreloaded = defaults.bool(forKey: "isPreloaded")
if !isPreloaded {
preloadData()
defaults.set(true, forKey: "isPreloaded")
}
}
但是,我想在应用程序更新时预装一个新的更新的CSV文件。我想我可以在默认设置中创建一个名为“isPreloaded2”的新密钥,但是CSV文件会随着每次更新而改变,我想知道是否有更好的方法。也许你可以在userDefaults中创建一个密钥
lastUpdatedVersion
,以检查哪个版本已经更新。
然后您可以检查以下内容:
let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"]
if !NSUserDefaults.standardUserDefaults.objectForKey(key: "lastVersionUpdated") || NSUserDefaults.standardUserDefaults.objectForKey(key: "lastVersionUpdated") != currentVersion
{
//Update your CSV here
//...
NSUserDefaults.standardUserDefaults.setObjectForKey(key: "lastVersionUpdated", object: currentVersion)
}
但这是否是一个优雅的解决方案,仍取决于您的决定 感谢乔拉的解决方案。对于任何感兴趣的人,以下是我如何在Swift中实现它: Swift 3.0
let defaults = UserDefaults.standard
if let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String {
let currentVersion = defaults.value(forKey: "currentVersion") as? String
if version != currentVersion { //currentVersion will either be nil or last version number when app is launched after update.
preloadData()
defaults.set(version, forKey: "currentVersion") //update currentVersion in defaults so version will match currentVersion next time.
}
}
在预加载新数据之前,不要忘记删除旧数据(my preloadData()函数包括removeData()函数)