Why does ARC retain method arguments?

See this reply from the Objc-language mailing list:

When the compiler doesn’t know anything about the
memory management behavior of a function or method (and this happens a
lot), then the compiler must assume:

1) That the function or method might completely rearrange or replace
the entire object graph of the application (it probably won’t, but it
could). 2) That the caller might be manual reference counted code, and
therefore the lifetime of passed in parameters is not realistically
knowable.

Given #1 and #2; and given that ARC must never allow an object to be
prematurely deallocated, then these two assumptions force the compiler
to retain passed in objects more often than not.

I think that the main problem is that your method’s body might lead to the arguments being released, so that ARC has to act defensively and retain them:

- (void) processItems
{
    [self setItems:[NSArray arrayWithObject:[NSNumber numberWithInt:0]]];
    [self doSomethingSillyWith:[items lastObject]];
}

- (void) doSomethingSillyWith: (id) foo
{
    [self setItems:nil];
    NSLog(@"%@", foo); // if ARC did not retain foo, you could be in trouble
}

That might also be the reason that you don’t see the extra retain when there’s just a single call in your method.

Leave a Comment