Objective c 如何从xib实例化视图?

Objective c 如何从xib实例化视图?,objective-c,Objective C,我在xib文件中有一个视图,我想将该视图放到一个窗口中。。。。我正在使用以下代码: - (void) popupNotificationWithTag:(NSString *)tag fade:(double)msFade lineOne:(NSString *)lineOneText lineTwo:(NSString *)lineTwoText { NotificationWindow *notificationWindow; NotificationWindow *tmpW

我在xib文件中有一个视图,我想将该视图放到一个窗口中。。。。我正在使用以下代码:

- (void) popupNotificationWithTag:(NSString *)tag fade:(double)msFade lineOne:(NSString *)lineOneText lineTwo:(NSString *)lineTwoText
{
    NotificationWindow *notificationWindow;
    NotificationWindow *tmpWindow;
    NSEnumerator *enumerator;

    // Walk the notification windows in the array
    enumerator = [self.notificationWindows objectEnumerator];
    if(enumerator)
    {
        while((tmpWindow = [enumerator nextObject]))
        {
            if([tmpWindow.tag isEqualToString:tag])
            {
                notificationWindow = tmpWindow;
            }
        }
    }

    // Make a new notification window
    if (!notificationWindow)
    {
        int width = [[NSScreen mainScreen] frame].size.width;
        int height = [[NSScreen mainScreen] frame].size.height;

        notificationWindow = [[NotificationWindow alloc] initWithRect:NSMakeRect(width - 420, height - 130, 400, 100)];
        NSNib *nib = [[NSNib alloc] initWithNibNamed:@"Notification" bundle: nil];
        NSArray *objects;
        [nib instantiateNibWithOwner:self topLevelObjects:&objects];
        [notificationWindow setContentView: [objects objectAtIndex:0]];

        [notificationWindow setTag:tag];         
        [self.notificationWindows addObject:notificationWindow];
    }

    // Display window
    [notificationWindow makeKeyAndOrderFront:nil];
    [notificationWindow display];
    notificationWindow.fadeOut = msFade;
    [notificationWindow setPrimaryText:lineOneText];
}
视图是xib文件中唯一的内容,因此我认为
objectAtIndex:0
应该可以,但我在该行收到一个
-[NSApplication setFrame:]:未识别的选择器发送到实例0x100508500
异常

更新我用以下代码块替换了该行:

    for (id obj in objects) {
        if ([[obj class] isSubclassOfClass:[NSView class]])
            [notificationWindow setContentView: obj];
    }

我隐约记得,笔尖有一个隐藏的第一个对象,代表第一个响应者(或其他什么)。试试objectAtIndex:1,看看是否有效。

我隐约记得NIB有一个隐藏的第一个对象,代表第一个响应者(或其他什么)。请改为尝试objectAtIndex:1,看看是否有效。

在您的
nib实例化之后设置一个断点,其所有者:self-topLevelObjects:&objects]行,并告诉我们您的
对象
数组的计数是否大于零。如果是,您能找出索引零处的项是什么类型的对象(
className
?)吗?告诉你怎么做。@MichaelDautermann-有两个对象,但顺序似乎是随机的。我发布的代码有时有效,其他代码则无效。我将发布一篇编辑文章来解决这个问题。
[[obj类]isSubclassOfClass:[NSView类]]
应该写为
[obj isKindOfClass:[NSView类]]
在您的
nib实例化之后设置一个断点,其所有者:self-topLevelObjects:&objects]行,并告诉我们您的
对象
数组的计数是否大于零。如果是,您能找出索引零处的项是什么类型的对象(
className
?)吗?告诉你怎么做。@MichaelDautermann-有两个对象,但顺序似乎是随机的。我发布的代码有时有效,其他代码则无效。我将发布一篇编辑文章来解决这个问题。
[[obj class]isSubclassOfClass:[NSView class]]]
应该写成
[obj isKindOfClass:[NSView class]]]
数组中有2个对象,设置为1有时有效,有时为0,看起来数组中对象的顺序是随机的。正如Michael在上面的评论一样,我将其标记为正确,因为它引导我找到了答案。数组中有两个对象,设置为1有时有效,设置为0有时有效,因此数组中对象的顺序是随机的。我将其标记为正确,因为它引导我找到了答案,正如迈克尔在上面的评论一样。