简体   繁体   中英

Obj-C & Cocoa: Variable is nil after applicationDidFinishLaunching:

In the interface for my AppDelegate I have the following property declaration:

@property (strong) NSArray *fileNamesInCurrentDirectory;

and then, in the implementation:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    [self setFileNamesInCurrentDirectory:[NSArray arrayWithObject:@"hello"]];

}

- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView {
    return [self.fileNamesInCurrentDirectory count];
}

When numberOfRowsInTableView is called, fileNamesInCurrentDirectory is nil . Why?

Thanks in advance.

Because as mentioned in the documentation

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification    

Sent by the default notification center after the application has been launched and initialized

Which means, I guess, that the application loads entirely, build all views and then call the method.

Is there any reason why you need your method call to occur after the application is loaded ?

It's not said that applicationDidFinishLaunching is called before numberOfRowsInTableView .

The first method to be called is the init method, then applicationDidFinishLaunching .

Use the init method to initialize all your variables, expect for those variables that are in the xib file so they're not already loaded. The outlets loaded from the xib can be initialized in applicationDidFinishLaunching (or awakeFromNib ).

It is as Ramy Al Zuhouri said, it's a matter of timing. Here are some of the methods that can be used at start up, so you can see the order that they execute:

@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];
}

The log shows this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM