weakSelf in dealloc
We all know that it is generally recommended to do simple cleanup in the dealloc
method.
A very important reason is that in the process of destroying an object, if an operation such as weak
is performed, it will cause a crash.
A common crash stack information may be similar to the following
1 | #0 0x00007ff833e02dba in __abort_with_payload () |
Generally, when you see words such as weak_register_no_lock
, you can immediately react, and a weak
reference is created during the process of object dealloc
.
If encountered during local debugging, the Xcode console will also display information similar to the following
objc[4271]: Cannot form weak reference to instance (0x60000337c280) of class B. It is possible that this object was over-released, or is in the process of deallocation.
A simple code example that causes a crash is as follows
1 | - (void)dealloc { |
If it were that simple, it would have been obvious at a glance. But the actual situation may be more complicated than we expected, such as
1 | - (void)func { |
Scenarios of this sequential call are still easy to spot.
But in actual projects, if the code is complicated, it may only be triggered when some branches are executed.
And if these logic branches are some extreme scenarios or abnormal scenarios, they may not be found during testing and appear in the production environment.
such as
1 | - (void)doReport { |
To sum up, in the dealloc
method, try to keep the logic as simple as possible to avoid complicated logic and difficult to troubleshoot.
On the other hand, it is also very important to do a good job of unit testing and to cover various exception branches.