Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do memory management properties affect cells of an array?

In my iPhone development book, I'm seeing some strange coding examples in regard to what an array does when objects are added to the array and when the whole array is released. One code example has the following properties on an instance array:

@property (nonatomic, retain) NSMutableArray* myArray;

The author adds an object to the array and, immediately after, releases his pointer to the object. Won't the array cell now point to garbage data? Unless, behind the scenes, the array cell retains the object when added.

SomeObject* someObject = [[SomeObject alloc] init];
[self.myArray addObject:someObject];
[someObject release];

The author also releases the the pointer to the array without first going through each array cell and releasing the individual objects. This is a memory leak unless, behind the scenes, each cell is sent a release message;.

- (void)viewDidUnload {
    self.myArray = nil;
    [super viewDidUnload];
}
like image 589
JoJo Avatar asked Nov 21 '25 16:11

JoJo


1 Answers

Unless, behind the scenes, the array cell retains the object when added.

Yes, this happens.

... unless, behind the scenes, each cell is sent a release message.

This also happens.

You have answered your own question.

Here is a quote from Collections Programming Topics:

And when you add an object to an NSMutableArray object, the object isn’t copied, (unless you pass YES as the argument to initWithArray:copyItems:). Rather, an object is added directly to an array. In a managed memory environment, an object receives a retain message when it’s added; in a garbage collected environment, it is strongly referenced. When an array is deallocated in a managed memory environment, each element is sent a release message.

like image 105
Tom Dalling Avatar answered Nov 24 '25 07:11

Tom Dalling



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!