Objective-c: Questions about self = [super init]

前端 未结 8 1199
鱼传尺愫
鱼传尺愫 2020-12-12 23:01


I have seen self = [super init] in init methods. I don\'t understand why. Wouldn\'t [super init] return the superclass? And if we point

8条回答
  •  北荒
    北荒 (楼主)
    2020-12-12 23:30

    @MartinR has a very good answer. But do you ever wonder why "[super init] calls the superclass implementation of init with the same (hidden) self argument. (This might be the point that you understood wrongly.)" works in his 3rd point ?

    Here is the excerpt from Big Nerd Ranch guide 3rd edition, chapter 2 Objective C that clarifies this point

    “How does super work? Usually when you send a message to an object, the search for a method of that name starts in the object’s class. If there is no such method, the search continues in the superclass of the object. The search will continue up the inheritance hierarchy until a suitable method is found. (If it gets to the top of the hierarchy and no method is found, an exception is thrown.)”

    “When you send a message to super, you are sending a message to self, but the search for the method skips the object’s class and starts at the superclass.”

    This code shows how iOS Runtime performs this task

    objc_msgSendSuper(self, @selector(init));
    

提交回复
热议问题