我注意到,当我重写 UIView
子类中的 init
和 initWithFrame:
时,这两个方法都会被调用。即使在我的代码中只有一个被显式调用:
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
为什么initWithFrame在init之前调用?
最佳答案
这不是问题。在 UIView 的情况下, [super init]
调用将自动更改为 [super initWithFrame:CGRectZero]
。因此,您必须牢记这一点来维护此代码。
关于ios - 为什么 UIView 会同时调用 init 和 initWithFrame?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19423182/