How does the iOS development-runtime implement the weak attribute?

Source: Internet
Author: User

features of the weak property:
Weak indicates that the attribute defines a "non-owning relationship" (nonowning relationship).
When you set a new value for the weak property, the set method neither retains the new value nor releases the old value.
Similar to assign, however, the property value is emptied (nil out) when the object being disposed of by the attribute.

runtime is how to realize the automatic nil of weak variable.

The weak object is placed in a hash table.
The object memory address pointed to by weak as key, and is dealloc when the reference count for this object is 0.
If weak point to the object memory address is addr, then the addr as the key, in this weak table search, find all addr as the key of the object, so set to weak.

Specific mechanisms:

Objc_storeweak (&weakpo, Model) function:

The Objc_storeweak function takes the memory address of the assignment object (Model) as the key value, and registers the memory address (& Weakpo) of the weak modified property variable (WEAKPO) as value in the weak table.

If model 0 (nil), the memory address of the variable (WEAKPO) (& Weakpo) is removed from the weak table.

Objc_storeweak (&weakpo, Model) can be understood as: Objc_storeweak (value, key), and when the key to nil, the value of nil.

In model Nil, WEAKPO and model point to the same memory address, in the model to nil, Weakpo change nil. Sending a message to Weakpo at this point does not crash: sending messages to nil in objective-c is safe.

Specific process objc/objc-weak.h Code link

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.