self和super

先假定有个Person类

#import <Foundation/Foundation.h>

@interface Person : NSObject

- (void)test;

@end

#import "Person.h"

@implementation Person

- (void)test
{
    NSLog(@"Person:%@---%@---%@---%@",[self class],[self superclass],[super class],[super superclass]);
}

@end

在test方法中分别输出:[self class],[self superclass],[super class],[super superclass]。

在定义一个Person的子类SubPerson

#import "Person.h"

@interface SubPerson : Person

@end

#import "SubPerson.h"

@implementation SubPerson

- (void)test
{
    [super test];

    NSLog(@"SubPerson:%@---%@---%@---%@",[self class],[self superclass],[super class],[super superclass]);
    //输出:SubPerson:SubPerson---Person---SubPerson---Person

    // self -> SubPerson
    // class:获取当前方法调用者的类
    // superclass:获取当前方法调用者的父类

    // super:仅仅是一个编译指示器,就是给编译器看的,不是一个指针
    // 本质:只要编译器看到super这个标志,就会让当前对象去调用父类方法,本质还是当前对象在调用

    /* 底层实现代码就说明super的确是一个标志
     objc_msgSendSuper({self, class_getSuperclass(objc_getClass("Person"))}, sel_registerName("description"));
     */

    NSLog(@"%@",self);
    //NSLog(@"%@",super); 不能打印
}

@end

现在分别创建一个Person和SubPerson的对象分别执行test方法

#import "ViewController.h"
#import "SubPerson.h"
#import "Person.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    SubPerson *sp = [[SubPerson alloc]init];
    [sp test];
    //输出:Person:SubPerson---Person---SubPerson---Person
    //输出:SubPerson:SubPerson---Person---SubPerson---Person

    Person *p = [[Person alloc]init];
    [p test];
    //输出:Person:Person---NSObject---Person---NSObject
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end

results matching ""

    No results matching ""