Search code examples
objective-creleaseretainautorelease

Is release needed for a reference turned from retain on autorelease object?


For the following code, 1 - is retain needed on the object returned back from getFoo; 2 - is the release needed on foo in method func?

- (NSString *)getFoo {
    return [[[NSString alloc] initWithString:@"foo"] autorelease];
}

- (void)func {
    // ??? is the retain needed?
    NSString *foo = [[self getFoo] retain];

    // use foo

    // ??? is the release needed?
    [foo release];
}

Solution

  • Every retain must be match with a release.

    This said, in your func you don't need to retain *foo if you are not delaying it's use. Usually autorelease pool get's drain at the end of the run loop so you have the time to use it locally in your function.
    But if you retain you must release.

    And you could do this :

    return [NSString stringWithString:@"foo];
    

    This is a convenience methode that return an autorelease object to you.