开发者

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


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.


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.


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜