1. The retainCount of UIViewController is different from what we see in some cases. For example, the following code:
2. UIView * mainView = xxx;
3. UIViewController * subVC = [[UIViewController alloc] init]; // retainCount = 1 in subVC
4. [mainView addSubview: subVC. view]; // here, subVC's retainCount = 3, added 2
Then later,
5. [subVC. view removeFromSuperview]; // here, the retainCount of subVC is 4; an increase of 1
6. [subVC release]; // here, the subVC reference count is 3, which is reduced by 1.
In fact, we expect that the subVC reference count will be 0 at the time of 6, and dealloc will be called, but not actually. So why?
To verify this problem, we save the pointer after 6:
UIViewController * temp = subVC;
As a global variable.
After a while, call temp. retainCount. The Code will crash at this time. What does this mean?
It indicates that temp is an invalid pointer.
This proves that UIViewController is delay when performing removeFromSuperView, and implements autorelease (for illustration purposes, maybe to prevent animation, it reduces all retainCount to 0.
Therefore, although the last retainCount is not 0, the code is correct and there is no memory leakage. Therefore, as long as the operation is performed in the opposite way as the allocation is added, the memory should be released.