Swift: Create an Array of Double values and save it to NSUserDefaults

試著忘記壹切 提交于 2019-12-11 17:14:55

问题


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")

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:

  1. On the console I see this: fatal error: Can't unwrap Optional.None (lldb)
  2. Highlighted on my code, I see this: Thread 1: EXC_BAD_INSTRUCTION...

And I don't know what I'm doing wrong or where should I look for more info about this...


回答1:


I think the type system gets confused by arrayForKey because really it still returns AnyObject!

I always hav a wrapper property:

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()
}
}


来源:https://stackoverflow.com/questions/24584972/swift-create-an-array-of-double-values-and-save-it-to-nsuserdefaults

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!