4

我正在对 UIView 进行子类化,试图从 nib 文件加载我在界面构建器中放置的视图。我在返回线上收到以下错误:

由于未捕获的异常“NSGenericException”而终止应用程序,原因:“此编码器要求从 initWithCoder 返回替换的对象:”

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

2 回答 2

14

你正在做一些非常奇怪的事情)

loadNibNamed:owner:options:将调用initWithCoder:从 xib 实例化您的视图。但是您是loadNibNamed:owner:options:initWithCoder:. 无限递归?

要从 xib 加载视图,您可以执行以下操作:

@implementation MyView

+ (MyView*) myView
{
  NSArray* array = [[NSBundle mainBundle] loadNibNamed:@"MyView" owner:nil options:nil];
  return [array objectAtIndex:0]; // assume that MyView is the only object in the xib
}

@end
于 2010-11-05T21:07:49.400 回答
0

而不是这样做self = [objects objectAtIndex:0],您应该遍历数组并确保获得正确的对象,例如:

for (id object in objects) {
    if ([object isKindOfClass:[YourClassName class]])
        self = (YourClassName*)object;
}   

就是说,我总是将这一层向上做,并将参考从UIViewController. 不过,这会破坏抽象层,因为只想使用视图的类需要知道 Nib 所在的位置:

UIViewController *vc = [[UIViewController alloc] initWithNibName:@"MyView" bundle:nil];
YourClassName* view = (YourClassName*)vc.view;
[vc release];
于 2010-11-05T19:37:03.060 回答