Ok, this is going to be a really embarrassing question, but I looked like mad in my beginner's books (especially those usually helpful indices) and behold, I did not find a down-to-earth explanation of what 'super' does in my applications.
I had a look at this here, but I'm afraid that's well beyond me. Can anyone of开发者_运维技巧fer a very simply explanation of what 'super' does in my apps and why I should become friends with it? E.g.:
- (void)viewDidLoad {
[super viewDidLoad];}
Thanks!!
super
calls the superclass's implementation of the method. So if your class inherits UIViewController
, then [super viewDidLoad];
will call the UITableViewController
class's viewDidLoad
method. You should usually do this because the super class may do important things that need to happen. In the case of viewDidLoad, I'm not sure it actually does anything currently, but it always could in a future version of the framework.
at the low level, self
contains a pointer to the set methods it responds to. this is a basic mechanism for the implementation of dynamic dispatch. each class is given a unique set. if you're familiar with c++, this is similar in concept to a virtual table. you can think of an objc method as being like a C function with 2 hidden arguments (self,_cmd).
super
is a dynamically created representation of self
, with a pointer to the next-in-line methods implemented by the instance's superclasses. this representation is based on self
, and just directs to another set of implemented methods.
@interface MONTypeA : NSObject
- (void)monMethod;
@end
@interface MONTypeB : MONTypeA
- (void)monMethod;
@end
@implementation MONTypeA
- (void)monMethod {
printf("i am MonTypeA\n");
}
@end
@implementation MONTypeB
- (void)monMethod {
[super monMethod]; /* << will call -[MONTypeA monMethod], which will print "i am MonTypeA\n" */
printf("i am MonTypeB\n");
}
@end
if you create an instance of MONTypeA
, then it will respond to monMethod
:
MONTypeA * a = [MONTypeA new];
[a monMethod];
[a release], a = 0;
// outputs: "i am MonTypeA\n"
MONTypeB * b = [MONTypeB new];
[b monMethod];
[b release], b = 0;
// outputs: "i am MonTypeA\n""i am MonTypeB\n" because -[MONTypeB monMethod] calls through super
therefore, calling super
performs the implementation of the method of the superclass in this specific case.
it is important to remember: the set of methods super
refers to is always those of the previous implementation of the method in the hierarchy, it is not the same set as the set of instance methods which an instance of the superclass would be given (unless your class were to override every method).
精彩评论