与NSUserDefault一起使用字符串数组的最佳实践 [英] Best Practice using an Array of Strings with NSUserDefault
问题描述
将字符串数组保存到userDefaults时遇到了一些麻烦.我在类中声明了一个字符串数组,并带有一个属性观察器来同步到userDefaults.此外,我希望将数组限制为最多5个字符串.
I'm having a bit trouble saving an array of strings to userDefaults. I have an Array of strings declaired in a class, with a property observer ment to sync to userDefaults. Furthermore, I want the array to be limited to a maximum of 5 Strings.
let userDefaults = NSUserDefaults.standardUserDefaults()
var suggestions: [String]! {
didSet {
var arrayEnd = suggestions.count
if arrayEnd >= 5 {
arrayEnd = 4
}
let newArray = Array(suggestions[0...arrayEnd])
userDefaults.setObject(newArray, forKey: "suggestions")
userDefaults.synchronize()
}
}
func getSuggestionData() {
if userDefaults.valueForKey("suggestions") != nil {
self.suggestions = userDefaults.valueForKey("suggestions") as? [String]
}
}
override func viewDidLoad() {
super.viewDidLoad()
getSuggestionData()
suggestions.insert("someString", atIndex: 0)
}
}
当我运行它时,我得到:
When i run this i get:
致命错误:解开可选值时意外发现nil
fatal error: unexpectedly found nil while unwrapping an Optional value
我尝试在数组中插入新对象的行上的
. 我尝试按照此线程中的方法进行操作,但没有将任何内容保存到列表中.
on the line where I try to insert a new object to the array. I have tried following the approach in this thread, but it didn't save anything to the list.
我是新手,并且可选类型不是我的强项,也许有人知道这是什么问题?
I'm new to swift, and optional-types aren't my strong side, maybe someone know what's wrong?
推荐答案
由于从用户默认值读取可能会返回nil
值,因此请使用可选绑定以确保安全:
As reading from user defaults could return nil
values, use optional binding to be safe:
func getSuggestionData() {
if let suggestionArray = userDefaults.objectForKey("suggestions") {
self.suggestions = suggestionArray
} else {
self.suggestions = [String]()
}
}
但是我建议使用具有定义的默认值的非可选变量.
But I'd recommend to use an non-optional variable with a defined default value.
在应用程序的AppDelegate
中,覆盖init()
或插入代码以注册键/值对.
In AppDelegate
of your app, override init()
or insert the code to register the key/value pair.
override init()
{
let defaults = NSUserDefaults.standardUserDefaults()
let defaultValue = ["suggestions" : [String]()];
defaults.registerDefaults(defaultValue)
super.init()
}
Registering the default keys and values is the way Apple suggests in the documentation.
- 如果尚未写入任何值,则读取默认值(空数组).
- 如果有值,则读取实际值
代替变量suggestions
的值观察器,实现一种方法来插入新值,删除最后一个值并将数组写入磁盘.
无需使用可选绑定,因为用户默认设置中的数组始终处于定义状态.
Instead of the value observer of the variable suggestions
implement a method to insert a new value, delete the last one and write the array to disk.
There is no need to use optional binding because the array in user defaults has always a defined state.
let userDefaults = NSUserDefaults.standardUserDefaults()
var suggestions = [String]()
func insertSuggestion(suggestion : String)
{
if suggestions.count == 5 { suggestions.removeLast() }
suggestions.insert(suggestion, atIndex: 0)
userDefaults.setObject(suggestions, forKey: "suggestions")
userDefaults.synchronize()
}
func getSuggestionData() {
suggestions = userDefaults.objectForKey("suggestions") as! [String]
}
override func viewDidLoad() {
super.viewDidLoad()
getSuggestionData()
insertSuggestion("someString")
}
旁注:
如果您不需要显式地使用键值编码方法,则永远不要使用valueForKey:
而不是objectForKey:
.
A side note:
never use valueForKey:
rather than objectForKey:
if you don't need explicitly the key-value-coding method.
这篇关于与NSUserDefault一起使用字符串数组的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!