objective-c - 在 initWithCoder 中获取 EXC_BAD_ACCESS

标签 objective-c macos cocoa

我在加载/创建新 View 表单 xib 文件时遇到问题。我得到 EXEC_BAD_ACCESS code=2 并且在我的调用堆栈上我看到 initWithCoder 方法的多次调用。我不明白为什么会发生这种情况,因为我只为我的类(class)调用了一次 alloc init 。 下面是我的代码:

@interface SongListView :  NSView
@property (nonatomic, strong) IBOutlet NSScrollView* view;
@end

@implementation SongListView

- (id)initWithFrame:(NSRect)frameRect
{
    self = [super initWithFrame:frameRect];

    if(self)
    {
        [self setup];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder: aDecoder];

    if(self)
    {
        [self setup];
    }

    return self;
}

- (void)setup
{
    NSArray *nib;

    [[NSBundle mainBundle] loadNibNamed:@"scrollTabViewItemWithTableView"
                                  owner:self
                        topLevelObjects:&nib];
    [self addSubview: self.view];
}

@end

这就是我创建 SongListView 的方式:

SongListView* tableView = [[SongListView alloc] init];

有人可以解释一下发生了什么,为什么我会多次调用 initWithCoder 方法,以及如何修复它?

最佳答案

一般来说,你的 NSView 子类不应该加载 XIB。它们应该位于 XIB 中(因此在 XIB 加载时创建)或在代码中创建。

在您的情况下,存在许多架构上奇怪的事情,但我怀疑崩溃是由于您在scrollTabViewItemWithTableView.xib 中有一个 SongListView 实例引起的,因此当您加载 XIB 时,您运行 setup 并加载 XIB 并运行安装程序 加载 XIB 并运行安装程序...

关于objective-c - 在 initWithCoder 中获取 EXC_BAD_ACCESS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21364113/

相关文章:

c - 在 macOS Sierra 上构建 guile-2.0.11 失败 : Undefined symbols for architecture x86_64

macos - 将 NSRange 内容转换为 NSString?

cocoa - 检测垂直 NSScroller 在 NSTableView 中触底

ios - iOS 中现有 appid 的推送通知

iphone - 最大线程限制?

objective-c - Xcode:将图像设置为 Touch Bar 上的按钮(适用于新 MacBook Pro)

macos - 无法为 NSMenuItem(FinderSync 扩展)设置子菜单

objective-c - 为什么我们都在 init 方法中检查 if(self)?

ios - 将多段线转换为可渲染的形状

Objective-C,如何定义按钮按下的处理程序?