简体   繁体   中英

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.

我认为问题在于,当您将一个对象添加到数组中时,该数组不会复制给定的对象,它仅保留对其的引用,并将保留计数增加一

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM