在我的AppDelegate的接口中,我具有以下属性声明:
@property (strong) NSArray *fileNamesInCurrentDirectory;
然后,在实现中:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
[self setFileNamesInCurrentDirectory:[NSArray arrayWithObject:@"hello"]];
}
- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView {
return [self.fileNamesInCurrentDirectory count];
}
[调用numberOfRowsInTableView
时,fileNamesInCurrentDirectory
为nil
。为什么?
谢谢。
由于documentation中所述
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
启动并初始化应用程序后,由默认通知中心发送
我想这意味着应用程序将完全加载,构建所有视图,然后调用该方法。
加载应用程序后,是否有任何原因需要您进行方法调用?
正如Ramy Al Zuhouri所说,这是时间问题。以下是一些可以在启动时使用的方法,因此您可以看到它们的执行顺序:
@implementation AppDelegate
- (id)init {
if (self = [super init])
NSLog(@"In init");
return self;
}
+(void)initialize {
NSLog(@"Initialize");
}
-(void)awakeFromNib {
NSLog(@"awakeFromNib");
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
NSLog(@"applicationDidFinishLaunching");
}
- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView {
NSLog(@"numberOfRowsInTableView");
return [self.fileNamesInCurrentDirectory count];
}
日志显示此:
2012-11-12 14:23:56.880 TableViewTimingProblem[1399:303] Initialize
2012-11-12 14:23:56.881 TableViewTimingProblem[1399:303] In init
2012-11-12 14:23:56.885 TableViewTimingProblem[1399:303] awakeFromNib
2012-11-12 14:23:56.893 TableViewTimingProblem[1399:303] numberOfRowsInTableView
2012-11-12 14:23:56.937 TableViewTimingProblem[1399:303] applicationDidFinishLaunching
不是说applicationDidFinishLaunching
在numberOfRowsInTableView
之前被调用。
首先要调用的方法是init
方法,然后是applicationDidFinishLaunching
。
使用init
方法初始化所有变量,并期望xib文件中的那些变量尚未被加载。从xib加载的插座可以在applicationDidFinishLaunching
(或awakeFromNib
)中初始化。