1

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.

1
  • You are adding multiple references in all to one array and emptying it each time through the loop. Try print(all) when you exit the loop to see what's happening. Commented Jul 15, 2016 at 12:34

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Use of explicit types are not recommended, better to use implicit: var all = NSMutableArray(). Also unlike Swift Arrays in NSMutableArray the value of the object doesn't get modified, so all can be a letvariable.
Thanks @VladimirNul, I made those changes to the code.
-1
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>>()

1 Comment

@TestO. Don't "reset" the inner array. You're storing a reference to it inside all, not a copy. That means anything you do to it after storing the reference applies to what's inside all too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.