添加到swift数组会覆盖最后一个对象

时间:2015-03-08 11:31:03

标签: ios arrays swift

我想不断向全局/常量数组添加值。问题是它只是不断覆盖最后一个值而不是将它添加到数组中,所以我总是得到2个值

全局数组

struct Globals {


        struct savedCalculationData {

            static var dataArray = ["something here"] 
        }
    }

保存到另一个类的数组

        //code to copy string value... 

        //Add to global array
        var copiedDataArray = Globals.savedCalculationData.dataArray
        copiedDataArray.append ("\(copyText)") <--- string value

        //Save array to defaults
        NSUserDefaults.standardUserDefaults().setObject(copiedDataArray, forKey: "savedDataArray")
        NSUserDefaults.standardUserDefaults().synchronize()

2 个答案:

答案 0 :(得分:1)

Array is copied when it's assigned to new variables起,您根本不会修改Globals.savedCalculationData.dataArray

你应append不复制:

Globals.savedCalculationData.dataArray.append("\(copyText)")
NSUserDefaults.standardUserDefaults().setObject(Globals.savedCalculationData.dataArray, forKey: "savedDataArray")

或将copiedDataArray写回Globals.savedCalculationData.dataArray

var copiedDataArray = Globals.savedCalculationData.dataArray
copiedDataArray.append ("\(copyText)")
Globals.savedCalculationData.dataArray = copiedDataArray
NSUserDefaults.standardUserDefaults().setObject(copiedDataArray, forKey: "savedDataArray")

答案 1 :(得分:1)

您将附加到全局数组的副本,但似乎没有将更新的数组设置回来,因此全局数组不会更改。

假设您希望在添加全局数据时保留全局数据,我建议您设计Globals结构以自动处理:

struct Globals {

    // Convenience variable for the standard defaults
    private static var Defaults: NSUserDefaults { return NSUserDefaults.standardUserDefaults() }

    struct SavedCalculationData {
        private static let DataArrayKey = "savedDataArray"
        static var dataArray: [String] {
            get {
                return Defaults.objectForKey(DataArrayKey) as? [String] ?? []
            }
            set {
                // This setter is called when the array contents change,
                // not just when a new array is set
                Defaults.setObject(newValue, forKey: DataArrayKey)
                Defaults.synchronize()
            }
        }
    }
}

然后,您可以更简洁地更新全局数据:

Globals.SavedCalculationData.dataArray.append(copyText)