Confundir el comportamiento de la memoria con un NSMutableArray 2D

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.

¿Es eso correcto?

preguntado el 01 de febrero de 12 a las 03:02

2 Respuestas

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.

Respondido 01 Feb 12, 07:02

it was adding a pointer of 'contents' to "outerArray' after you do [outerArray addObject:contents];

contents retain will +1,

so you do

[contents release]; contents = nil;

it just make contents retain -1 and let contents (it's a pointer) point to nil

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

will not occur any error

Respondido 01 Feb 12, 07:02

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.