[SuperInit] may have three of the results:The first type: [SuperINIT] Initialized successfully, this is the most normal situation. The second type: [SuperINIT] Initialization failed, we all know that OC's two-step creation, alloc open up memory space,Init initializes the object, butThere is another role for INIT, when initialization fails,The init method returns a nil. Back to the top of the line, if self for nil, then if ( The contents of the span class= "Hljs-keyword" >self) statement will not be executed, ensuring that the program is robust and secure. -(Instancetype) init {self = [ Super init]; //call the designated initializer if (self) {//Custom initialization} return
self; The Third Kind:
self = [super init] after execution, The memory points to an unrelated address. The occurrence of this situation is generally a few cases: Singleton, class family, the object is nsnumber type, the parent class at the time of initialization to release the current object, and then re-opened the new memory address.
Why to use [super init]
Use the words "Zen and objective-c programming Art" to answer:这样做,你看你会得到一个不能用的对象,并且它的行为是不可预测的,最终可能会导致你的 app 发生 crash。
用通俗易懂的话回答:
if( self = [super init] )这是一种通常的建议写法,赋值并测试nil只是为了防止超类在初始化过程中发生改变,返回了不同的对象。
About Objective-c's Super init