Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to return an array

I never seem to get this right. I've got a method that returns a mutable array. What is the proper way to return the array and avoid potential memory leaks?

If I plan to store the results locally inside another view controller, does that affect the way the array should be returned?

Lastly, what if it's just an non-mutable array? Does that require a different technique?

thanks, Howie

like image 484
Ward Avatar asked Oct 14 '25 15:10

Ward


2 Answers

If your method does not have alloc or copy in the name then the proper thing is to return a autoreleased version of the array. Also, you should return a copy of the array to prevent modifications to your local copy

- (NSMutabalArray*] mutableArray {
    return [[myArray mutableCopy] autorelease];
}

- (NSArray*] array {
    return [[myArray copy] autorelease];
}

Return an auto-released object. If you've created your array with any alloc/init/copy methods - you should send autorelease message to array before returning it (something like return [myArray autorelease];). Otherwise arrays created with factory methods (arrayFrom... arrayWithContentsOf...) return autoreleased object so you don't need to worry about memory leaks there.

You should read about memory management and retain count on apple dev site. There might be some other initialization methods that retain returned object which would 'cause a memory leak.

like image 26
Eimantas Avatar answered Oct 17 '25 12:10

Eimantas



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!