Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusing memory behavior with a 2D NSMutableArray

This is my first question on Stack Overflow, and I hope it's pretty simple. I have the following code that I wrote to figure out exactly what I'm adding to 'outerArray' in this case:

NSMutableArray *contents = [[NSMutableArray alloc] initWithContentsOfFile:path];
outerArray = [[NSMutableArray alloc] initWithCapacity:2];
[outerArray addObject:contents];

[contents removeObjectAtIndex:0];
[contents release];
contents = nil;

NSMutableArray *test = [outerArray objectAtIndex:0];

NSLog(@"Test at 0: %@", [test objectAtIndex:0]);

Now, the confusing part is this: What I see is the element originally at index 1 of 'contents' being written out by NSLog. This doesn't make sense to me:

  • If I was adding a copy of 'contents' to 'outerArray', then I would expect 'test' to contain that copy and it would output the original 0th element of 'contents'.
  • If I was adding a pointer to 'contents' to 'outerArray', then I would expect the NSLog line to throw an error.

The only thing I can think is that I am adding a pointer to 'contents' to 'outerArray', but that releasing it doesn't overwrite the data. So, I'm basically lucky at this point that the NSLog isn't failing, but it could, later.

Is that correct?

like image 548
Dan Parish Avatar asked Jan 22 '26 10:01

Dan Parish


1 Answers

What you see is correct: NSMutableArray retains objects added to it, so contents remains live even though your code has released its reference to it. The second reference (from inside outerArray) is what holds your inner array formerly known as contents from being released. There is no copying involved.

like image 137
Sergey Kalinichenko Avatar answered Jan 25 '26 13:01

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!