2015-10-18 56 views
1

我想将nsmutabledictionaries添加到我的nsmutablearray中,但是当addobject被执行时,它会用新的覆盖之前的数据。如果我尝试添加一个字符串,它工作正常,但如果我尝试添加nsmutabledictionary它不能正常工作。我知道这个问题之前已经说过,但似乎我无法用迅速的语言找到它。这是我下面的代码:NSMutableArray addObject覆盖数据SWIFT

@IBAction func logAction(sender: UIButton) { 

    let buttonRow = sender.tag 
    let product_name = data2[buttonRow].name 
    let product_price = data2[buttonRow].price 
    let product_id = data2[buttonRow].id 

    productDictionary["product_name"] = product_name 
    productDictionary["price"] = product_price 
    productDictionary["id"] = product_id 

    let string = product_name 
    productArray.addObject(productDictionary) 

    print(productArray, "order ends here") 

} 

我已经为全局以下变量:

var productArray = NSMutableArray() 
var productDictionary = NSMutableDictionary() 

我到底错在这里做什么?

+0

是否有一个特别的原因,你为什么要使用NSMutableArray和NSMutableDictionary而不是Swift的本地'Array'和'Dictionary'类型? – NRitH

+0

我使用NSMutableArray和NSMutableDictionary的原因是我需要制作一个数组,其中包含字典和数组字典中的字典。例如,在我调用这个函数的特定视图控制器中,我需要构造一个包含其中的字典的数组,然后将此数组添加到另一个数组中。我试图使用本地数组和字典,但我无法处理它。我不能找到嵌套数组和字典的好教程,所以...... – user3882720

+0

你当然可以用Swift本机类型来做到这一点,但与Objective-C不同,你必须指定它们包含的数据的类型。要创建一个类似于你的'productDictionary'的字典,我假设它具有用于键的字符串和用于值的字符串,您可以像'var productDictionary = [String:String]()'一样初始化它。要创建这些数组,你可以使用var productArray = [[String:String]]()'。纯粹从文体的角度来看,您可能只需简单地将“产品”和数组“产品”称为字典。 – NRitH

回答

2

每次调用logAction()时,都会改变全局值的值productDictionary。由于NSArray不存储副本您添加到它的值,您只需每次添加另一个参考到全局字典。如果你要坚持使用NSMutableArray s和NSMutableDictionary(请参阅我对原始帖子的评论),然后摆脱全局productDictionary,而改为创建一个新的,每次调用logAction()。换句话说,更换

productDictionary["product_name"] = product_name 
productDictionary["price"] = product_price 
productDictionary["id"] = product_id 
productArray.addObject(productDictionary) 

var productDictionary = NSMutableDictionary() 
productDictionary["product_name"] = product_name 
productDictionary["price"] = product_price 
productDictionary["id"] = product_id 
productArray.addObject(productDictionary) 

又是什么let string = product_name办?

+0

这解决了我的问题。谢谢。字符串变量仅用于测试。非常感谢你。 – user3882720