为什么两个init函数都被调用 [英] Why do both init functions get called

查看:94
本文介绍了为什么两个init函数都被调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个像这样设置的类来自定义UIView。



@interface myView:UIView

   - (id)init { 
self = [super init];
if(self){
[self foo];
}
return self;
}

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if(self){
//初始化代码
[self foo];
}
return self;
}


- (void)foo {
//在此处构建UIView
}
pre>

如果我使用

$ f
$ b

  * aView = [[myView alloc] init]]; 

  myView * aView = [[myView alloc] initWithFram:aFrame]; 


解决方案

UIView init call UIView initWithFrame:。因为你覆盖了两个,调用 init 方法会导致调用 initWithFrame:方法:



换句话说:你的 init 调用 UIView init UIView init 呼叫 initWithFrame:。因为你重载 initWithFrame:,你的 initWithFrame:被调用,依次调用 UIView initWithFrame: 。



解决方案,因为 initWithFrame: init 方法中删除对 foo 的调用。


If I have a class that is setup like this to customize a UIView.

@interface myView : UIView

- (id)init {
    self = [super init];
    if(self){
        [self foo];
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        [self foo];
    }
    return self;
}


-(void) foo{
   //Build UIView here 
}

How come foo is called twice whether I use

myView *aView = [[myView alloc]init]]; 

or

myView *aView = [[myView alloc]initWithFram:aFrame]; 

解决方案

UIView init calls UIView initWithFrame:. Since you override both, calling your init method results in your initWithFrame: method being called:

In other words: your init calls UIView init. UIView init calls initWithFrame:. Since you override initWithFrame:, your initWithFrame: is called which in turn calls UIView initWithFrame:.

The solution, since your initWithFrame: will always be called, is to remove the call to foo from your init method.

这篇关于为什么两个init函数都被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆