Is “self” weak within a method in ARC?

后端 未结 2 514
情歌与酒
情歌与酒 2020-12-10 07:30

I have a method that occasionally crashes.

-(void)foo{
    [self doSomething];
    [self.delegate didFinish];
    [self doSomethingElse];
}

2条回答
  •  清歌不尽
    2020-12-10 07:41

    self is neither weak nor strong. If you can access self then you are in the scope of a method call, and that method call is being performed by somebody via a reference they must own. self is implied to be a valid reference as long as it's in scope, and it is implied that any memory management or ownership is handled by the caller.

    When calling a method through a weak reference, ARC will retain the object for the duration of that method call (see this answer). With strict compiler warnings enabled, you will actually be forced to create a strong reference before sending any methods to that reference.

    So by definition, if a method is being called on an object, the caller must already have ownership and nothing needs to be done.

    Of course, it is possible to end up calling methods on deallocated objects but that is the result of bad caller code.

提交回复
热议问题