我在一个小的iPhone应用程序上工作,我使用NSUserDefaults作为我的数据持久性。它只需要跟踪一些东西,比如一些名字和一些数字,所以我想我最好保持简单。
我找到了这个页面作为参考,但我不认为它能回答我的问题。基本上,我希望能够检查一个值(或一个键)是否已经存在于NSUserDefaults,然后做相应的事情。
一些例子:应用程序启动,如果这是它第一次启动,它会输出一个警告说欢迎。要判断这是否是第一次打开,它会读取UserDefaults并进行检查。
例2:它说,“Hello [Name]”,其中Name是您已输入的内容。如果你已经打开了应用程序,没有名字,它应该说“Hello World”。我需要检查你是否已经输入了一个名字,并采取相应的行动。名称将存储在NSUserDefaults中。
有人帮忙吗?我真的很感激!
Swift 3 / 4:
这里是Int/Double/Float/Bool键值类型的一个简单扩展,它模拟了通过UserDefaults访问的其他类型的可选返回行为。
(2018年8月30日编辑:从Leo的建议中更新了更高效的语法。)
extension UserDefaults {
/// Convenience method to wrap the built-in .integer(forKey:) method in an optional returning nil if the key doesn't exist.
func integerOptional(forKey: String) -> Int? {
return self.object(forKey: forKey) as? Int
}
/// Convenience method to wrap the built-in .double(forKey:) method in an optional returning nil if the key doesn't exist.
func doubleOptional(forKey: String) -> Double? {
return self.object(forKey: forKey) as? Double
}
/// Convenience method to wrap the built-in .float(forKey:) method in an optional returning nil if the key doesn't exist.
func floatOptional(forKey: String) -> Float? {
return self.object(forKey: forKey) as? Float
}
/// Convenience method to wrap the built-in .bool(forKey:) method in an optional returning nil if the key doesn't exist.
func boolOptional(forKey: String) -> Bool? {
return self.object(forKey: forKey) as? Bool
}
}
它们现在与其他内置的get方法(字符串、数据等)更加一致。只需使用get方法来代替旧的方法。
let AppDefaults = UserDefaults.standard
// assuming the key "Test" does not exist...
// old:
print(AppDefaults.integer(forKey: "Test")) // == 0
// new:
print(AppDefaults.integerOptional(forKey: "Test")) // == nil