Is “self” weak within a method in ARC?

 ̄綄美尐妖づ 提交于 2019-11-28 10:20:48

self would be strong within a method, allowing the function to complete. Is self weak or strong?

self is neither strong nor weak in ARC. It is assumed that the caller holds a reference, and self is unsafe unretained.

It's also true that self can be -dealloced within its own method under ARC, and it's regarded as "Undefined Behavior (or at least dangerous)" for your program to do this.

What would the reasoning be for it being strong or weak?

It's unretained for Performance -- to avoid what is (in the vast majority of cases) an unnecessary reference count inc/dec. Even if they did all those extra ref count operations, your program would still be susceptible to such problems in multithreaded programs or in the presence of a race condition (also UB). So this is one of those extreme edge cases they (rightly) determined they need not defend themselves from.

Is there documentation on this?

Of course! :)

Mike Weller

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!