在情节提要中实例化Xib时对initWithCoder进行无休止的递归调用 [英] Endless recursive calls to initWithCoder when instantiating xib in storyboard

查看:73
本文介绍了在情节提要中实例化Xib时对initWithCoder进行无休止的递归调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了在整个应用程序(基于情节提要)中重复使用某个子视图,我决定将子视图构建为笔尖,然后将其加载.为此,我做了以下事情:

In order to re-use a certain subview throughout my application (which is storyboard based), I decided to build the subview as a nib, and load it in. To do this, I have done the following:

我有一个可以调用Widget的UIView子类.我创建了一个相应的xib文件,将File owner属性设置为新的子类,并连接IBOutlets.

I have a UIView subclass we can call Widget. I create a corresponding xib file, set the File owner property to my new subclass, hook up the IBOutlets.

然后,在我的情节提要中,我在视图控制器内部拥有一个uiview,并将其类设置为我创建的Widget类.

Then, in my storyboard, I have a uiview inside of a view controller, and I set its class to the Widget class I created.

在小部件类中,我重写initWithCoder,并在其中加载笔尖,如下所示:

Within the widget class, I override initWithCoder, and in there load the nib as follows:

-(id)initWithCoder:(NSCoder *)aDecoder{
    if ((self = [super initWithCoder:aDecoder])){
        [self addSubview:[[[NSBundle mainBundle] loadNibNamed:@"Widget" owner:self options:nil] objectAtIndex:0]];
    }
    return self;
}

应用程序此时将崩溃,并在此处设置一个断点表明initWithCoder被一遍又一遍地调用.

The app would crash at this point, and setting a break point here revealed that initWithCoder was being called over and over again.

在这种情况下,我似乎混合了两种使用笔尖的方法,但是我不清楚出错的地方.如有必要,我可以抛出一个堆栈跟踪,但这基本上是对同一函数的无尽嵌套调用.

It seems like I have mixed two methods for using a nib in this situation, but I'm unclear as to where I went wrong. I can throw up a stack trace if necessary, but it's basically endless nested calls to the same function.

推荐答案

您是否碰巧将.xib文件中视图的自定义类"设置为小部件"?

Did you happen to set the View's "Custom Class" in your .xib file to "Widget"?

这将解释您看到的行为,因为initWithCoder:是从xib加载的所有事物的初始化程序:

That would explain the behaviour you're seeing, because initWithCoder: is the initializer for all things loaded from a xib:

  1. 从xib加载包含Widget对象的父视图
  2. 调用Widget的initWithCoder:方法,并尝试加载Widget xib
  3. 小部件xib包含带有自定义的UIView 类"Widget",因此,再次使用初始化Widget对象 initWithCoder:
  1. Your parent view, which contains a Widget object, is loaded from the xib
  2. The Widget's initWithCoder: method gets called, and tries to load the Widget xib
  3. The Widget xib contains a UIView with the Custom Class "Widget", so again, a Widget object is being initialized with initWithCoder:, etc.

如果确实如此,您要做的就是在小部件的xib中删除UIView的自定义类"条目.

If that is indeed the case, all you have to do is remove the "Custom Class" entry for the UIView in your Widget's xib.

这篇关于在情节提要中实例化Xib时对initWithCoder进行无休止的递归调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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