Upload
vonbo
View
2.222
Download
0
Tags:
Embed Size (px)
DESCRIPTION
explain self and super in objc's class
Citation preview
Obj-C中的self与super
twitter:@vonbo
11年1月24日星期一
输出结果?
11年1月24日星期一
输出结果?
11年1月24日星期一
输出结果?
self class is Derivedsuper class is Derived
11年1月24日星期一
obj-c的方法调用• [self class] or [super class]
• self 是类的隐藏的参数,指向当前当前调用方法的对象
• super是一个“编译器指示符”,它和self指向的是相同的消息接收者,不同的是,super告诉编译器,当调用class的方法时,要去调用父类的方法,而不是本类里的
11年1月24日星期一
C函数方法调用 -1
• Sending Messages
• 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.
11年1月24日星期一
C函数方法调用 -2• 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.uperclass of an instance of a class.
11年1月24日星期一
objc_msgSend
• 函数定义:• id objc_msgSend(id theReceiver, SEL
theSelector, ...)
• [self class]:
• theReceiver -> self
• SEL -> class
11年1月24日星期一
objc_msgSendSuper
• 函数定义:• id objc_msgSendSuper(struct objc_super
*super, SEL op, ...)
• [super class]
• objc_super -> some struct?
• SEL -> class
11年1月24日星期一
objc_super
struct objc_super {
id receiver;
Class superClass;
}
11年1月24日星期一
objc_msgSendSuper
• [super class]:
• 构建objc_super结构体,receiver = self,superClass = Base
• 调用objc_msgSendSuper方法,通过objc_super -> superClass找到selector
• 将此selector作用到objc_super -> receiver上
11年1月24日星期一
That is ...• [self class]
• objc_msgSend(receiver, class)
• receiver = Derived, “class” selector is from NSObject
• [super class]
• objc_msgSendSuper(objc_super, class)
• ==> objc_msgSend(objc_super -> receiver, class)
• receiver = Derived, “class” selector is from NSObject
• NSObject的这个class方法,就是返回receiver的class
11年1月24日星期一
That is ...
• [self class]
• objc_msgSend(receiver, class)
• receiver = Derived, class method is from NSObject
• [super class]
• objc_msgSendSuper(objc_super, class)
• ==> objc_msgSend(objc_super -> receiver, class)
• receiver = Derived, class method from NSObject
• NSObject的这个class方法,就是返回receiver的class
So ... [self class] ‘s output is Derived [super class] ‘s output is Derived too !
11年1月24日星期一
How to get super class’s name?
• [self superclass]
• NSLog(@"super class is %@", [self superclass]);
• The output is “Base” !
11年1月24日星期一
The End
11年1月24日星期一