從這個(gè)經(jīng)典的案列入手
@implementation Son : Father
- (id)init
{
self = [super init];
if (self)
{
NSLog(@"%@", NSStringFromClass([self class]));
NSLog(@"%@", NSStringFromClass([super class]));
}
return self;
}
@end
這個(gè)答案是什么呢。開(kāi)始的時(shí)候嘀咕自沧,兒子坟奥,老子?但想想應(yīng)該不是這么簡(jiǎn)單拇厢,誠(chéng)然爱谁,確實(shí)沒(méi)有不是坑的題,先嘀咕著,不看答案孝偎。
這是關(guān)于消息的官方解釋
When it encounters a method invocation, the compiler might generate a call to any of several functions to perform the actual message dispatch, depending on the receiver, the return value, and the arguments. You can use these functions to dynamically invoke methods from your own plain C code, or to use argument forms not permitted by NSObject’s perform… methods. These functions are declared in /usr/include/objc/objc-runtime.h.
- objc_msgSend sends a message with a simple return value to an instance of a class.
- objc_msgSend_stret sends a message with a data-structure return value to an instance of a class.
- objc_msgSendSuper sends a message with a simple return value to the superclass of an instance of a class.
- objc_msgSendSuper_stret sends a message with a data-structure return value to the superclass of an instance of a class.
看不懂访敌,繼續(xù)往下,這里就要清楚Object-c里的消息機(jī)制衣盾。我們都知道消息機(jī)制的底層:
OBJC_EXPORT void objc_msgSend(void /* id self, SEL op, ... */ )
__OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0);
OBJC_EXPORT void objc_msgSendSuper(void /* struct objc_super *super, SEL op, ... */ )
這里就大概看得出寺旺,[self class]是調(diào)用的objc_msgSend,而[super class]調(diào)用的是objc_msgSendSuper势决。如果前面的很常見(jiàn)阻塑,哪后面的到底是個(gè)什么鬼大爺。
我們先看看objc_super
struct objc_super {
id receiver;
Class superClass;
};
receiver還是我們的兒子對(duì)象果复,而superClass就是你猜的他老漢陈莽。
但我們執(zhí)行[super class]。大概內(nèi)部執(zhí)行的邏輯是:
- 首先去老漢那去找這個(gè)方法据悔。是否存在传透,如果不存在就繼續(xù)讓上找。
- 在這里极颓,我們都沒(méi)有去實(shí)現(xiàn)這個(gè)class朱盐,所以找來(lái)找去在仙人那NSObject那找到了。
而我們的[self class]也是一樣的菠隆。從自己這開(kāi)始找兵琳,然后去老漢那狂秘,一直往上,直到仙人那躯肌,最后都在仙人那相遇了者春。但我們的receiver都是兒子。所以他們折騰來(lái)回清女,還是最終執(zhí)行的同一個(gè)方法钱烟,同一個(gè)接受者。所以結(jié)果自然也一樣嫡丙,打印出來(lái)都是Son拴袭。
為了驗(yàn)證這個(gè),請(qǐng)看下例
@interface GrandFather : NSObject
- (NSString *)name;
@end
@implementation GrandFather
- (NSString *)name {
return [NSString stringWithFormat:@"grandfather:%@",NSStringFromClass([self class])];
}
@end
@interface Father : GrandFather
@end
@implementation Father
- (NSString *)name {
return [NSString stringWithFormat:@"father:%@",NSStringFromClass([self class])];
}
@end
@interface Son : Father
@end
@implementation Son
- (NSString *)name {
return [NSString stringWithFormat:@"son:%@",NSStringFromClass([self class])];
}
- (void)showName {
NSLog([NSString stringWithFormat:@"%@,%@",[self name],[super name]]);
}
@end
如果我這樣調(diào)用
Son *son = [Son new];
[son showName];
這個(gè)看下結(jié)果就明了曙博。