Why does ARC retain method arguments?

后端 未结 4 1555
再見小時候
再見小時候 2020-11-29 07:48

When compiling with ARC, method arguments often appear to be retained at the beginning of the method and released at the end. This retain/release pair seems superfluous, and

4条回答
  •  甜味超标
    2020-11-29 08:19

    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.

提交回复
热议问题