问题描述
有人可以帮我理解为什么我们在初始化之前先在 super
上调用初始化方法的原因.我在UIView的子类中遇到了一段代码,想知道在这里总是调用myMethod,这意味着我没有在 UIView
中设置框架,那么为什么我们要这样做并使用 if
条件.
Can someone help me understanding as why do we call an initialization method on super
first before initializing. I came across a piece of code in a subclass of UIView and wanted to know that here myMethod is always getting called that means I am not getting the frame set in UIView
, then why are we doing this and using an if
condition.
self = [super initWithFrame:CGRectMake(0, 0, 20, 100)];
if(self != nil) {
[self myMethod:data];
self.backgroundColor = [UIColor clearColor];
}
return self;
推荐答案
假设我有一个名为 SpinningView
的 UIView
子类.创建 spinningView
的代码如下所示:
Let's say I have a UIView
subclass called SpinningView
. The code to create spinningView
would look like this:
SpinningView * spinner = [[SpinningView alloc] initWithFrame:CGRectMake(0.0,0.0,20.0,20.0)]
现在让我们看一下SpinningView的 -initWithFrame:
方法的实现
Now let's take a look at the implementation of SpinningView's -initWithFrame:
method
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
self.backgroundColor = [UIColor clearColor];
}
return self;
}
第一行是简单的分配.我们将自己分配给 -UIView
的 -initWithFrame:
The first line is simple assignment. We're assigning ourselves to the result of UIView
's implementation of -initWithFrame:
我们使用if语句查看self甚至是否有效.如果不是,我们将其退回.如果是这样,我们对其进行配置.
We use the if statement to see if self is even valid. If it's not we just return it. If it is, we configure it.
这篇关于在超类上调用-initWithFrame:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!