关于Super

关于Super


  • 何为super

[super xxx] calls the super method on the current instance (i.e. self).
[super xxx] ,表示接收xxx消息的对象是self,但是xxx方法的实现是super的。

http://stackoverflow.com/questions/11827720/why-does-self-class-super-class
  • 一个网上很有名的面试题:下面的代码输出结果是什么?
@implementation Son : Father
- (id)init
{
    self = [super init];
    if (self)
    {
        NSLog(@"%@", NSStringFromClass([self class]));
        NSLog(@"%@", NSStringFromClass([super class]));
    }
    return self;
}
@end

// 答:都是son。
  • 解答:
    1. 所有类的class实例方法都继承自NSObject,来自NSObject Protocol
    2. [super class]代表向Son发送class消息,但class方法的实现来自Father。
    3. 由于Father没有重写class方法,所以沿着继承链向上,最终调用NSObject的实现。
    4. 同理,由于Son也没有重写class方法,所以最终调用的也是NSObject的实现。
    5. 所以,[self class][super class]调用同一个对象(Son)的同一个方法(NSObject的class),它们的返回结果必定相同
    6. 根据文档的定义,class方法Returns the class object for the receiver’s class.(返回消息接收对象所属类的类对象),所以结果都是Son。

你可能感兴趣的:(关于Super)