Search code examples
iosswiftnsmutablearraynsmutabledictionary

After adding element in NSMutableArray previous elements gets replaced


I'm working on app in which I want to create array with number of NSDictionary's. When i'm trying to add NSMutableDictionary in NSMutableArray, previously added elements of that array get replaced. I don't know what is happening. Code as follows:

var paynowArray = NSMutableArray()
let tempDict = NSMutableDictionary()
for i in 0...selectedEmenetsArray.count-1 {
    tempDict.removeAllObjects()
    tempDict.setValue(selectedIdAry[i], forKey: "serviceId")
    tempDict.setValue(selectedAmountAry[i], forKey: "serviceAmount")              
    paynowArray.add(tempDict)
}
print(paynowArray)

While printing array last added NSMutableDictionary printed n times.

Thanks in advance.


Solution

  • Create tempDict inside the for loop. You should allocate dictionary for every element. Else you are replacing the same memory location value every times.

    var paynowArray = NSMutableArray()
    for i in 0...selectedEmenetsArray.count-1 {
    
        var tempDict = NSMutableDictionary()
    
        tempDict.setValue(selectedIdAry[i], forKey: "serviceId")
        tempDict.setValue(selectedAmountAry[i], forKey: "serviceAmount")              
        paynowArray.add(tempDict)
    }
    print(paynowArray)