简体   繁体   English

NSMutableArrays仅存储2个对象

[英]NSMutableArrays store only 2 objects

I have a weird problem - my mutable array stores only 2 objects - its count is 1,2,2,2 and doesn't change. 我有一个奇怪的问题-我的可变数组仅存储2个对象-它的数量是1,2,2,2并且没有变化。 My only observation is that it always replaces old values fx I have: value1 - 2, value2 - 4 and I add next object fx 66 and my array look like this: value1 - 4, value2 - 66. Here is some code: 我唯一的观察是,它总是替换我拥有的旧值fx:value1-2,value2-4,然后添加下一个对象fx 66,我的数组如下所示:value1-4,value2-66。这是一些代码:

func appendArrays(product: NSString, bPrice: NSString, sPrice: NSString) {
    defaults.synchronize()
    if prodArr.count == 0 {
        prodArr = NSMutableArray(array: [defaults.valueForKey(keys.keyProduct)!])
        bpArr   = NSMutableArray(array: [defaults.valueForKey(keys.keyBPrice)!])
        spArr   = NSMutableArray(array: [defaults.valueForKey(keys.keySPrice)!])
    }

    prodArr.addObject(product)
    bpArr.addObject(bPrice)
    spArr.addObject(sPrice)

    defaults.setObject(prodArr, forKey: keys.keyProduct)
    defaults.setObject(bpArr, forKey: keys.keyBPrice)
    defaults.setObject(spArr, forKey: keys.keySPrice)

    defaults.synchronize()
    NSLog("%i",[defaults.valueForKey(keys.keyBPrice)!].count)
}

This is occurring because you're declaring the arrays inside the scope of the function, thus they get destroyed each time you call the method. 发生这种情况是因为您在函数范围内声明了数组,因此每次调用该方法时它们都会被破坏。

Instead declare them at the top of your swift file, just after the Class name, so that they are properties. 而是在类名称之后,在swift文件的顶部声明它们,以便它们成为属性。

Of course you can have not more than two objects because your spArr is declared locally and it means that you create a new spArr object each time you call appendArrays . 当然,您不能有两个以上的对象,因为您的spArr是在本地声明的,这意味着您每次调用appendArrays时都会创建一个新的spArr对象。 You need to create it var spArr: NSMutableArray = NSMutableArray() outside the function and instead of doing: 您需要在函数外部创建它var spArr: NSMutableArray = NSMutableArray()而不是这样做:

spArr   = NSMutableArray(array: [defaults.valueForKey(keys.keySPrice)!])

do

spArr.addObject([defaults.valueForKey(keys.keySPrice)!])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM