Why in Objective-C, we use self = [super init] instead of just [super init]?

后端 未结 4 1278
南旧
南旧 2020-12-16 17:22

In a book, I saw that if a subclass is overriding a superclass\'s method, we may have

self = [super init];

First, is this supposed to be do

4条回答
  •  暖寄归人
    2020-12-16 18:04

    Understand that the object is already alloced and self points to a memory.

    Now [super init] does the initialization part.

    1) If initialization is successful self points to same object before initialization

    2) If initialization is failure init function returns nil and self = nil. Now we can check whether object is initialized and if yes do our magic by this code

     if(self = [super init]){
      // do our magic
     }
    

    IT is just like we use an imageView, we normally use

    UIImageView imgView = [[UIImageView alloc] init];
    

    imgView will only have non nil value if both alloc and init is succesful.

提交回复
热议问题