Objective-C中的self和super详解

0x01 self

当调用对象方法时,编译器都会默认传入一个指向本对象的指针,所以不同的对象都会调用到正确的成员变量。

这个指针就是self,它的值就是new时在堆中分配内存的首地址。

用在方法中时,哪个对象调用该方法self指针就指向哪个对象,可以把它当作调用该方法的那个对象的指针一样使用。

Whenever you’re writing a method implementation, you have access to an important hidden value, self. Conceptually, self is a way to refer to “the object that’s received this message.” It’s apointer, just like the greeting value above, and can be used to call a method on the current receiving object.

  • 谁调用了当前方法,self就代表谁:self出现在对象方法中,self就代表对象;self出现在类方法中,self就代表类;
  • 在对象方法中利用"self.成员变量名"可以访问当前对象内部的成员变量;
  •  [self 方法名]可以调用对象的方法/类方法。

0x02 super

self是一个隐藏参数变量,指向当前调用方法的对象,而super并不是隐藏参数,只是编译器的指令符号。

使用self调用方法时,self先从当前类中寻找方法,如果没有寻找到再去父类中寻找。

而super直接在父类中寻找方法。

There’s anotherimportant keyword available to you in Objective-C, called super. Sending a message to super is a way to call through to a method implementation defined by a superclass further up the inheritance chain. The most common use of super is when overriding a method.

最终都会搜索完整个继承链。所以, [self class]和[super class]输出是一样的。

扫描二维码关注公众号,回复: 2705228 查看本文章

0x03 self和super的配合使用

self = [super init] 是再熟悉不过的一行代码了,简单的一行代码足以看出self和super 的关键作用。

Objective-C的继承特性,使子类继承父类时能够获得相关的属性和方法。

所以在子类的初始化方法中,必须首先调用父类的初始化方法,完成父类相关资源的初始化。

[super init]去self的super中调用init:方法, 然后super会调用其父类的init:方法,以此类推,直到找到根类NSObject中的init:方法。然后根类中的init:方法负责初始化内存区域,添加一些必要的属性,返回内存指针,沿着继承链指针从上到下进行传递,同时在不同的子类中可以向内存添加必要的属性。最后到达当前类中,把内存地址赋值给self参数。

如果调用[super init]失败的话,将通过判断self来决定是否执行子类的初始化操作。

猜你喜欢

转载自blog.csdn.net/qq_33737036/article/details/81457159