Test O.
Test O.

Reputation: 221

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.

Upvotes: 1

Views: 157

Answers (2)

vacawama
vacawama

Reputation: 154583

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.

Upvotes: 2

Daniel Poulsen
Daniel Poulsen

Reputation: 1456

var all:NSMutableArray = NSMutableArray()
var i = 0
for ..........{
    let localArray:NSMutableArray = NSMutableArray()    
    /* Add objects to localArray */
    localArray.addObject("1\(i)")
    all.addObject(localArray)
    localArray.removeAllObjects() /* To reset the array after adding to  `all` array*/
    i+=1
}

but i would recommend to use Swift Array

like so

var all = Array<Array<Type>>()

Upvotes: -1

Related Questions