iPhone - 从nib文件加载UIView?

时间:2010-11-05 17:28:44

标签: iphone objective-c uiview subclassing

我正在子类化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];
}

2 个答案:

答案 0 :(得分:13)

你做的事很奇怪)

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

答案 1 :(得分: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];