cocoa:我应该使用哪种方法初始化属性而不是awakeFromNib

时间:2012-09-04 06:14:02

标签: macos cocoa

enter image description here

TableData是NSObject的子类,作为基于视图的表的数据源和表委托。 TableData的awakeFromNib方法将运行多次,因为我正在使用基于视图的表。如果TableData是NSViewController的子类,我可以使用loadView:来完成我的任务,但TableData是NSObject的子类,我的问题是:

  1. 我应该使用哪种方法代替awakeFromNib来初始化TableData属性?

2 个答案:

答案 0 :(得分:1)

我不知道你是如何创建窗口的,但你可以这样做:

AppDelegate.m

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    // Insert code here to initialize your application

    fMainWinDelegate = nil;
    fMainWinDelegate = [[MainWinDelegate alloc] init];
    [fMainWinDelegate showWindow];
}

MainWindowDelegate.m

- (id)initWithWindow:(NSWindow *)AWindow
{
    NSLog(@"MainWinDelegate::initWithWindow");
    self = [super initWithWindow:AWindow];
    if (self) {
        // Initialization code here.
        NSLog(@"MainWinDelegate::initWithWindow, we have self!");
    }

    return self;
}

- (void)awakeFromNib 
{
    NSLog(@"MainWinDelegate::awakeFromNib");
    // only for debug and to be sure that is called many times
}

- (void)showWindow {
    NSLog(@"MainWinDelegate::showWindow");

    if (!self.window) {
        [NSBundle loadNibNamed:@"MainWin" owner:self];

        NSLog(@"MainWinDelegate::showWindow init part");
        // do your init here
    }

    [self.window makeKeyAndOrderFront:self];

    NSLog(@"MainWinDelegate::showWindow end");
}

这是日志:

MainWinDelegate::initWithWindow
MainWinDelegate::initWithWindow, we have self!
MainWinDelegate::showWindow
MainWinDelegate::awakeFromNib
MainWinDelegate::showWindow init part
MainWinDelegate::showWindow end

答案 1 :(得分:0)

您可以选择:

@interface MONTableData : NSObject

// a designated initializer:
- (id)init;
- (id)initWithCoder:(NSCoder *)pCoder;

// or when the `TableData`'s input data source is set:
- (void)setPhotoAlbum:(MONPhotoAlbum *)pPhotoAlbum;

@end