我注意到当我覆盖init和initWithFrame时:在UIView子类中,两个方法都被调用.即使在我的代码中只有一个是显式调用:
TestViewController.m:
@implementation TestViewController
- (void)viewDidLoad
{
[super viewDidLoad];
View1 *view1 = [[View1 alloc] init];
[self.view addSubview:view1];
}
@end
View1.m:
@implementation View1
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
NSLog(@"initWithFrame");
}
return self;
}
- (id)init
{
self = [super init];
if (self)
{
NSLog(@"init");
}
return self;
}
@end
控制台看起来像这样:
2013-10-17 12:33:46.209 test1[8422:60b] initWithFrame
2013-10-17 12:33:46.211 test1[8422:60b] init
为什么在init之前调用initWithFrame?
解决方法
原因是View1中的initWithFrame:你调用[super initWithFrame:].
UIView initWithFrame:调用[self init].
UIView initWithFrame:调用[self init].
在类中调用方法时,将调用子类上的方法.
因此,当您在UIView上调用实例方法(例如init)时,它会尝试在View1上调用init方法(如果已实现).
根据以下答案编辑:https://stackoverflow.com/a/19423494/956811
让view1成为View1的一个实例.
调用层次结构是:
- [view1(View1) init]
- [view1(UIView) init] (called by [super init] inside View1)
- [view1(View1) initWithFrame:CGRectZero] (called inside [view(UIView) init] )
- [view1(UIView) initWithFrame:CGRectZero] (called by [super initWithFrame] inside View1)
- ...
- NSLog(@"initWithFrame"); (prints "test1[8422:60b] initWithFrame")
- NSLog(@"init"); (called inside [view1(View1) init] ; prints "test1[8422:60b] init")
检查OOP中的继承.
http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)
http://www.techotopia.com/index.php/Objective-C_Inheritance