Pierre
Pierre

Reputation: 11633

Memory Management with method calls

I have a quite simple question about memory management in Objective-c and methods calling.

Imagine I have :

- (void)someFunction
{
    NSMutableArray *array = [NSMutableArray arrayWithObjects:@"Value 1", nil];
    [self someOtherFunction:array];
}

- (void)someOtherFunction:(NSMutableArray *)array
{
    // Should I retain array here?
    [array addObject:@"Value 2"];
    // And then release ?
}

This is a simple exemple but imagine we have like 10 method calls with the same object parameter. What's the best solution ?

Upvotes: 2

Views: 70

Answers (2)

Stephen Darlington
Stephen Darlington

Reputation: 52565

If you're being all belt-and-braces or are doing lots of odd things with threads then you should probably retain/release inside each method call. In fact, this is exactly what ARC does for you behind the scenes. (It's not documented as far as I know and may change from version to version.)

And, certainly, it won't do any harm to retain/release as you suggest. In practice it's unlikely to add much of an overhead.

Having said all that: most people don't add the retain/release. If your code is all running on the main thread it's very unlikely that your object will be released while you're executing your method.

Upvotes: 1

adig
adig

Reputation: 4057

(This explains reference counting for the case when ARC is disabled)

When using convenience constructors, the retured objects are returned as autoreleased objects.

Autorelease means that at the end of the current runloop the object's reference count will be decreased by 1. If the object wasn't retained from the creation to this point, that means that it will be deallocated.

This means that in your code you don't need to add any retain / release calls as the object will live until the end of your someFunction method.

If by the end of your someFunction method you need to keep your array living, in a instance variable for example, you can retain it using :

_myInstanceVar = [array retain]; // don't forget to release it in dealloc method

Upvotes: 0

Related Questions