SNV*_*NV7 1 iphone inheritance objective-c ipad ios
只是有一个noob问题.我试图理解调用自我和超级之间的区别.现在我理解了继承和其他基本的OOP概念,但自我和超级的想法对我来说仍然不清楚.我将以一个例子来说明我的问题.
因此,当手机颠倒时,以下代码执行segue.我知道"Scene2ViewController"是"UIViewController"的子类,因此"Scene2ViewController"继承了UIViewController的所有方法.所以下面我调用方法performSegueWithIdentifier,消息的接收者是self.现在,当我将"self"更改为"super"时,代码仍以相同的方式执行.是不是称自己超级呼唤自己?如果有人能向我解释这一点,将不胜感激,谢谢.
//Scene2ViewController.m
- (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation
{
if (interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) {
[self performSegueWithIdentifier:@"SegueToScene1" sender:self];
}
return (interfaceOrientation ==
UIInterfaceOrientationPortrait);
}
Run Code Online (Sandbox Code Playgroud)
self而super实际上都指向同一个对象.super是一个关键字,它告诉编译器生成指令,这些指令开始在超类而不是当前类中搜索方法定义.
@interface A : NSObject {}
- (void)foo;
@end
@implementation A
- (void)foo {
NSLog(@"A's foo!");
}
@end
@interface B : A
@end
@implementation B
- (void)foo {
NSLog(@"B's foo!");
}
@end
//...somewhere in a method of class B...
[self foo]; // prints "B's foo" in the console
[super foo]; // prints "A's foo" in the console
Run Code Online (Sandbox Code Playgroud)
如果我们根据注释假设最后一行是B方法中的某个地方,那么self指向B的某个实例super也指向同一个B实例.但是当你self用来调用时foo,搜索一个实现的foo从B类开始.使用时super,搜索a foo以B的超类A开头.
super当你想要保留继承的行为,但添加一些东西时,它会特别方便.因此,我们可以使用B实现foo调用A的版本[super foo].如果super没有办法调用继承的方法,并且foo从重写的方法调用将导致无限递归.
当你调用的方法self(或者更确切地说,将消息发送给self在Objective-C项),运行时将搜索方法的继承层次结构中的实现,首先self,上去过NSObject.因此,如果self实现该方法,它将被执行.如果没有,super将检查班级,依此类推.
发送消息super非常相似,但运行时将开始寻找实现super和跳过self.
| 归档时间: |
|
| 查看次数: |
1783 次 |
| 最近记录: |