thary
thary

Reputation: 221

Objective-C - How to add objects in 2d NSMutableArrays

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

Upvotes: 1

Views: 2799

Answers (5)

Dustin Pfannenstiel
Dustin Pfannenstiel

Reputation: 562

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.

Upvotes: 0

Ben Zotto
Ben Zotto

Reputation: 71008

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.

Upvotes: 3

Ed Marty
Ed Marty

Reputation: 39690

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.

Upvotes: 2

TechZen
TechZen

Reputation: 64428

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.

Upvotes: 0

GuidoMB
GuidoMB

Reputation: 2211

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

Upvotes: 0

Related Questions