objective-creleaseautoreleaseretaincount

release returned object or do i have to use autorelease


sample code:

- (Foo*)createFoo {
    Foo *foo = [[Foo alloc] init];
    return foo;
}

- (void)someOtherMethod {
    Foo *foo;
    foo = [self createFoo]; //retain count 1
    [foo release]; //retain count = 0 => object gets released?

    //repeat
    foo = [self createFoo];
    [foo release];
}

Question: Do i have to autorelease in createFoo or can i release the returned object in someOtherMethod?


Solution

  • Your code in this instance should be autoreleasing your object as you are handing over ownership to the calling code, you no longer wish to be responsible for it within the method and so you should relinquish your retain on it.

    Remember NARC - methods that begin with these keywords are assumed to NOT autorelease...

    New, Alloc, Retain, Copy

    If your method were named newFoo or copyFoo then your code above would be fine without autoreleasing.