Mark
Mark

Reputation: 33

Releasing object being returned the right way?

If I am creating an object inside of a function and returning it, when/where should I release this object? Here is an example where I am creating an object.

- (NSDictionary*) sampleFunction
{
    NSMutableDictionary* state = [[NSMutableDictionary alloc] initWithCapacity:5];

    [state setObject:[[NSNumber alloc] initWithInt:self.a]  forKey:@"a"];
    [state setObject:[[NSNumber alloc] initWithInt:self.b] forKey:@"b"];
    [state setObject:[[NSNumber alloc] initWithInt:self.c] forKey:@"c"];

    return state;
}

Additional question: In order to avoid memory leaks am I also supposed to release the NSNumbers allocated here as well? What would this code look like without memory leaks?

Upvotes: 3

Views: 60

Answers (1)

lxt
lxt

Reputation: 31294

Firstly, you should go to this guide for all the rules:

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html

...don't take what people say on here as gospel. There are some exceptions and odd rules the guide I linked to above will clarify.

Now, relating to your example: broadly speaking, every time you alloc something you must release it. When you're returning a value from a method, it should be autoreleased (99% of the time. There are a couple of exceptions: see, nothing is every easy!). Apple provide some auto-released methods for convenience - NSNumber has one of these.

I'm going to show you your code above, but rewritten to use those autoreleased methods:

- (NSDictionary*) sampleFunction
{
    NSMutableDictionary* state = [NSMutableDictionary dictionaryWithCapacity:5];

    [state setObject:[NSNumber numberWithInt:self.a]  forKey:@"a"];
    [state setObject:[NSNumber numberWithInt:self.b] forKey:@"b"];
    [state setObject:[NSNumber numberWithInt:self.c] forKey:@"c"];

    return state;
}

As I mentioned, you can also use autorelease with alloc/init:

NSMutableDictionary* state = [[[NSMutableDictionary alloc] initWithCapacity:5]autorelease];

Again, the Apple document I've linked to above is the best place to go for answers to memory management questions.

Upvotes: 1

Related Questions