Problem
The weak variable is automatically set to nil when the reference count is 0 o'clock, how is this feature implemented?
Answer
In Friday QA, there is a special introduction to weak implementation principle. Https://mikeash.com/pyblog/friday-qa-2010-07-16-zeroing-weak-references-in-objective-c.html
The relevant content is also presented in the book "Objective-c Advanced Programming".
Simply put, the system has a global CFMutableDictionary instance that holds a list of weak pointers for each object, because each object may have more than one weak pointer, so the value of this instance is CFMutableSet type.
All we have to do is to go to the global dictionary, find all the weak pointers, and set the value to nil when the reference count becomes 0. How do we do that? Friday QA describes a method similar to KVO implementation. When the object has a weak pointer, we can point this instance to a newly created subclass, and then modify the release method of the subclass, in the release method, go to the Global CFMutableDictionary dictionary to find all the weak object, and set to nil. I extracted the core code for the implementation of Friday QA, as follows:
Class subclass = Objc_allocateclasspair (class0= Class_getinstancemethod (class = Class_getinstancemethod (class, @selector (Dealloc)); Class_addmethod (Subclass, @selector ( Release), (IMP) Customsubclassrelease, method_gettypeencoding (release)), Class_addmethod (Subclass, @selector ( Dealloc), (IMP) Customsubclassdealloc, method_gettypeencoding (Dealloc)); Objc_registerclasspair (subclass);
Of course, this does not mean that Apple is officially implemented, because this part of Apple's code is not open source. The open source code in the GNUStep project is described in the book "Objective-c Advanced Programming", and the idea is similar. So I think that although the implementation of the details will be different, but the general implementation of ideas should be very different.
Complete the full text.
The next issue of the interview question:
We know that the properties of UI controls that are dragged from Storyboard to the compiler are weak as follows:
@property (Weak, nonatomic) *mybutton;
So, if there are some UI controls that we want to create in code, should it use weak or strong? Why?
IOS face Question (v): Weak's internal realization principle--transfer from Tang Qiao