views:

448

answers:

5

Hello, I have this code

    NSMutableArray *insideArray = [[NSMutableArray alloc] init];
NSMutableArray *outsideArray = [[NSMutableArray alloc] init];
[insideArray addObject:@"Hello 1"];
[insideArray addObject:@"Hello 2"];
[outsideArray addObject:insideArray];
[insideArray removeAllObjects];
[insideArray addObject:@"Hello 3"];
[insideArray addObject:@"Hello 4"];
[outsideArray addObject:insideArray];

The current output is

    array(
      (
       "Hello 3",
       "Hello 4"
       ),
      (
       "Hello 3",
       "Hello 4"
       )
      )

I need a way to get the output to be

    array(
      (
       "Hello 1",
       "Hello 2"
       ),
      (
       "Hello 3",
       "Hello 4"
       )
      )

Does anyone have a solution or could see where i've gone wrong? Thanks

A: 

I think that the problems is that when you add an object into an array, the array does not copy the given object, it just holds a reference to it and increments the retain count by one

GuidoMB
A: 

Well, you're deleting the "Hello 1" and "Hello 2" from the insideArray which is the actual object held by outsideArray. In other words, the outsideArray has no knowledge of the contents of insideArray.

TechZen
+2  A: 

You're using the same NSMutableArray for both sub-arrays. You need to use two different objects. Specifically, instead of

[insideArray removeAllObjects];

instead use

[insideArray release];
insideArray = [NSMutableArray array];

for the quickest solution.

Ed Marty
Thanks this worked great
thary
+2  A: 

You're only actually creating two arrays here. You're creating the "outside" array, and then adding two references to the same inner array to it. When you output it, you're seeing those two inner arrays referencing exactly the same thing.

You need to create more than one inner array here, since you expect them to hold different sets of values.

The key point here is that the arrays are just object references, and emptying and refilling the array doesn't create a new one; it just changes the one you've already got.

quixoto
A: 

Think about it from the standpoint of memory management. Each time you type "insideArray" the computer sees a reference a single point of memory. While "[outsideArray addObject:insideArray];" does place a reference to the insideArray object in outsideArray, insideArray still points to the same place in memory.

Try instantiating a new object and placing that in outsideArray. Change: [outsideArray addObject:insideArray];

to read: [outsideArray addObject:[NSMutableArray arrayWithArray:insideArray]];

That should be the simplest solution.

Dustin Pfannenstiel