读书人

OC中self跟super

发布时间: 2012-09-29 10:30:01 作者: rapoo

OC中self和super

?在 Objective-C 中的类实现中经常看到这两个关键字 ”self” 和 ”super”,以以前 oop 语言的经验,拿 c++ 为例,self 相当于 this,super 相当于调用父类的方法,这么看起来是很容易理解的。以下面的代码为例://

?上面有简单的两个类,在子类PersonMe中调用了自己类中的setAge和父类中的setName,这些代码看起来很好理解,没什么问题。

然后我在setName:andAge的方法中加入两行:

NSLog(@"self ' class is %@", [self class]);
NSLog(@"super' class is %@", [super class]);

??? 这样在调用时,会打出来这两个的class,先猜下吧,会打印出什么?按照以前oop语言的经验,这里应该会输出:

self ' s class is PersonMe
super ' s class is Person

??? 但是编译运行后,可以发现结果是:

self 's class is PersonMe
super ' s class is PersonMe

??? self 的 class 和预想的一样,怎么 super 的 class 也是 PersonMe?

真相

??? self 是类的隐藏的参数,指向当前当前调用方法的类,另一个隐藏参数是 _cmd,代表当前类方法的 selector。这里只关注这个 self。super 是个啥?super 并不是隐藏的参数,它只是一个“编译器指示符”,它和 self 指向的是相同的消息接收者,拿上面的代码为例,不论是用 [self setName] 还是 [super setName],接收“setName”这个消息的接收者都是 PersonMe* me 这个对象。不同的是,super 告诉编译器,当调用 setName 的方法时,要去调用父类的方法,而不是本类里的。

??? 当使用 self 调用方法时,会从当前类的方法列表中开始找,如果没有,就从父类中再找;而当使用 super 时,则从父类的方法列表中开始找。然后调用父类的这个方法(从super出现的在的方法所在的类的父类开始查找。)

文档解释:


#import <Foundation/Foundation.h>@interface High:NSObject-(void)negotiate;@end@implementation High-(void)negotiate{NSLog(@"High");}@end@interface Mid : High-(void)makeLastingPeace;@end@implementation Mid-(void)negotiate{NSLog(@"Mid");}-(void)makeLastingPeace{[super negotiate];}@end@interface Low : Mid@end@implementation Low-(void)negotiate{NSLog(@"Low");}@endint main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];Low* l=[[Low alloc] init];[l makeLastingPeace];[l release]; [pool drain]; return 0;}

?

//打印结果为high

另见参考:

http://blog.csdn.net/datacloud/article/details/7275170

读书人网 >移动开发

热点推荐