Is the returned object returned correctly?

If I create an object inside a function and return it, when / where should I let go of this object? Here is an example where I create 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 should I also release the NSNumbers allocated here? What would this code look like without memory leaks?

+3
source share
1 answer

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

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

... do not accept what people say here as the gospel. There are some exceptions and odd rules that will explain the manual associated with the above.

, : , , alloc -, . , autoreleased (99% . : ., !). Apple - NSNumber .

, , :

- (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;
}

, autorelease alloc/init:

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

, Apple, , .

+1

All Articles