iOS 中self和super如何理解?
或许你理解self和super都是指的是类的对象 self指的是本类的对象,而super指的是父类的对象,但是事实情况呢,可能有些和你想象的不一样?
简单看下下面例子:
@interface Person:NSObject { NSString* name; } - (void) setName:(NSString*) yourName; @end @interface PersonMe:Person { NSUInteger age; } - (void) setAge:(NSUInteger) age; - (void) setName:(NSString*) yourName andAge:(NSUInteger) age; @end @implementation PersonMe - (void) setName:(NSString*) yourName andAge:(NSUInteger) age { [self setAge:age]; [super setName:yourName]; NSLog(@"self ' class is %@", [self class]); NSLog(@"super' class is %@", [super class]); } @end int main(int argc, char* argv[]) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; PersonMe* me = [[PersonMe alloc] init]; [me setName:@"asdf" andAge:18]; [me release]; [pool drain]; return 0; }
按照之前的理解,很简单得出结论:
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是一个隐私参数,熟悉C的都知道,他和 _cmd构成方法的参数,self是动态的;执行时调用RT的objc_msgSend();
super是个编译器的指令符号,只是告诉编译器在执行的时候,去调谁的方法.super是编译的;执行时调用RT的objc_msgSendSuper();
英文解释如下:
self refers to the object receiving a message in objective-C programming.
Invoking a method on the self searches for the method implementation of the method in the usual manner, starting in the dispatch table of the receiving object’s class.
Example: [self startThread]; self.hostReach = YES; BOOL value = self.hostReach;
1.self is also a variable name that can be used in any number of ways, even assigned a new value. 2.Inside an instance method, self refers to the instance; but inside a class method, self refers to the class object.
super is a flag that tells the compiler to search for the method implementation in a very different place. It begins in the superclass of the class that defines the method where super appears.
Wherever super receives a message, the compiler substitutes another messaging routine for the objc_msgSend function. The substitute routine looks directly to the superclass of the defining class—that is, to the superclass of the class sending the message to super—rather than to the class of the object receiving the message.Messages to super allow method implementations to be distributed over more than one class.
For some tasks, each class in the inheritance hierarchy can implement a method that does part of the job and passes the message on to super for the rest. The init method, which initializes a newly allocated instance, is designed to work like this. Each init method has responsibility for initializing the instance variables defined in its class. But before doing so, it sends an init message to super to have the classes it inherits from initialize their instance variables. Each version of init follows this procedure, so classes initialize their instance variables in the order of inheritance.