Objective-C - weak property - getter autoreleases (Automatic Reference Counting)

删除回忆录丶 提交于 2019-12-04 10:16:46

Supplying weak on a property assumes __weak ownership for the ivar, i.e. it's just an instruction for @synthesize.

According to http://clang.llvm.org/docs/AutomaticReferenceCounting.html §4.2, reading __weak variable requires retaining the object (and releasing after, of course):

Reading occurs when performing a lvalue-to-rvalue conversion on an object lvalue.

  • For __weak objects, the current pointee is retained and then released at the end of the current full-expression. This must execute atomically with respect to assignments and to the final release of the pointee.
  • For all other objects, the lvalue is loaded with primitive semantics.

It does not say why, but think of what happens if the object you got from __weak variable dies before you even started using it. The purpose of weak pointer is to make sure you have either nil or a valid object with well-known lifetime, that is why reading its value implies retaining the pointee (and then property's getter returns it autoreleased).

This is not unique to Obj-C, it's common idiom to all weak pointer implementations (both refcounted and garbage collected). Weak pointers can not give out pointer value directly, they have to create strong pointer to 'hold' object to make sure it won't die before caller has even started using it. In Obj-C, it's retain-autorelease; in C++, weak_ptr creates shared_ptr first, in garbage-collected environments, a strong reference is returned and the object's lifetime is prolonged silently.

Getter for x1 looks like:

function -[B xa1] {
    var_8 = rdi;
    var_0 = rsi;
    rdi = objc_loadWeakRetained(var_8 + *_OBJC_IVAR_$_B.xa1);
    rax = [rdi autorelease];
    return rax;
}

So when you get property in

A* a3 = b1.xa1;

a1 == b1.xa1 get autorelease call and retained by autoreleasepool

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