-4

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.

sagar ss
  • 23
  • 7

2 Answers2

1

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)
Subramanian P
  • 4,365
  • 2
  • 21
  • 25
0

Should be inside the loop..

let tempDict = NSMutableDictionary()
Bilal
  • 18,478
  • 8
  • 57
  • 72