Ale*_*nko 3 xcode objective-c ios
我是Objective-C的新手,不明白为什么我们需要使用[super dealloc],[super viewDidLoad]或[super viewWillAppear:animated].当我创建示例代码应用程序时,我看到这样的事情:
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
Run Code Online (Sandbox Code Playgroud)
实际上Xcode 4总是为每个自动生成的方法添加超级方法.为什么?
或者当我使用dealloc方法时.为什么我需要在最后添加[super dealloc]?
- (void)dealloc
{
[nameField release];
[numberField release];
[sliderLabel release];
[super dealloc];
}
Run Code Online (Sandbox Code Playgroud)
PS现在我研究"开始iPhone 4开发".并且没有找到关于此方法的任何参考:(
cli*_*hlt 10
关键是,您通过继承它们来创建子类,在您的情况下,这似乎是一个自定义ViewController,例如MyViewController从UIViewController继承数据和方法.继承意味着,即使您没有指定它们,您的类也将具有父类具有的所有方法.例如:
@interface Foo : NSObject
- (void) doSomething;
@end
@interface Bar : Foo
@end
Run Code Online (Sandbox Code Playgroud)
然后以下是有效的
Bar *myBar = [[Bar alloc] init];
[myBar doSomething];
Run Code Online (Sandbox Code Playgroud)
即使您没有声明该方法,也可以在超类中找到它,因此调用了超类方法.
现在假设你有以下内容:
@interface Bar : Foo
-(void) doSomething;
@end
Run Code Online (Sandbox Code Playgroud)
两者的实施都是
@implementation Foo
- (void) doSomething
{
NSLog(@"This is a super important method that HAS TO BE CALLED IN ANY CASE");
}
@end
@implementation Bar
-(void) doSomething
{
NSLog(@"Well this is important, but not as important as Foos implementation");
}
@end
Run Code Online (Sandbox Code Playgroud)
如果没有a [super doSomething],那么永远不会调用超级重要的方法,因为您已在自定义实现中覆盖它.所以,当你做一个
Bar *myBar = [[Bar alloc] init];
[myBar doSomething];
Run Code Online (Sandbox Code Playgroud)
编译器不会看到Foo的doSomething中包含的完全重要的代码,因为您自己在类中提供了该方法,因此只会调用Bar的版本.
因此,每当您覆盖一个方法时,必须确保在必须调用它时调用基类版本,这对于该dealloc方法尤为重要,因为这将释放基类在初始化期间可能获得的任何内存.
| 归档时间: |
|
| 查看次数: |
2075 次 |
| 最近记录: |