Test O. Test O. - 4 months ago 17
iOS Question

NSMutableArray inside NSMutableArray Swift

I'm trying to store NSMutableArray inside NSMutableArray.
So

var all:NSMutableArray = NSMutableArray()
let localArray:NSMutableArray = NSMutableArray()
var i = 0
for ..........{

/* Add objects to localArray */
localArray.addObject("1\(i)")
/* Add localArray to all Array */
all.addObject(localArray)
/* Reset the array after adding to `all` array */
localArray.removeAllObjects()
i+=1
}


But the result: variable all which is NSMutableArray is reseted.

Answer

Unlike Swift's native arrays (which are structs and thus value types), NSMutableArrays are objects (reference types). By clearing out the mutable array after adding it to the other array, you are clearing out the only copy of that object.

If you move the declaration of localArray to inside your loop, you will get a new instance of the array each time through the loop and you will achieve the behavior you are looking for:

let all = NSMutableArray()
var i = 0
for ..........{
    let localArray = NSMutableArray()

    /* Add objects to localArray */
    localArray.addObject("1\(i)")
    /* Add localArray to all Array */
    all.addObject(localArray)

    i += 1
}

Note that I have removed the code which clears out localArray because that is no longer necessary since you get a new array each time through the loop.

Comments