问题描述
在我正在开发的应用程序,我需要(当用户输入一个不同的值的钱,这是一个双和变化),以创建将存储变量的值的数组。这样的想法是创建一个从NSUserDefaults的关键数组变量:
In the app I'm developing, I need to create an array that will store values of a variable (money, which is a double and changes when the user inputs a different value). So the idea was to create an array variable from a NSUSerDefaults key:
var moneyArray:Array = NSUserDefaults.standardUserDefaults().arrayForKey("MoneyArray")
然后我需要追加值,因此:
Then I needed to append the value so:
moneyArray.append(money)
而现在我会再次保存数组:
And now I would save the array again:
NSUserDefaults.standardUserDefaults().setObject(moneyArray,forKey:"MoneyArray")
在中间,我被印刷阵列看到的值。但我不能执行此code。每当我运行应用程序,出现这种情况:
In the middle, I was printing the array to see the values. But I can't execute this code. Whenever I run the app, this happens:
- 在我看到这个控制台:致命错误:无法解开Optional.None
(LLDB) - 突出了我的code,我看到:线程1:EXC_BAD_INSTRUCTION ...
和我不知道我做错了或者我应该寻找更多这方面的信息...
And I don't know what I'm doing wrong or where should I look for more info about this...
推荐答案
我觉得类型系统得到由arrayForKey困惑,因为实际上它仍然返回AnyObject!
I think the type system gets confused by arrayForKey because really it still returns AnyObject!
我总是甲肝包装属性:
var myArray : Array<Double>! {
get {
if let myArray: AnyObject! = NSUserDefaults.standardUserDefaults().objectForKey("myArray") {
println("\(myArray)")
return myArray as Array<Double>!
}
return nil
}
set {
println(myArray)
NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: "myArray")
NSUserDefaults.standardUserDefaults().synchronize()
}
}
这篇关于斯威夫特:创建双值的数组,并将其保存到NSUserDefaults的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!