I'm having an issue with a label not updating correctly in my UI. I have an Mac OS X app which uses a outline view to switch views. I want to simply have the date displayed to the user in a label on the view which is switched to (FirstViewController). When implemented alone in a new project I have no issue. But when implemented where the view changes, the value of the label does not update, in fact the console output indicates that _dateLabel is (null) even after being set prior. Any suggestions? I must be missing something quite fundamental!
Console output:
2014-08-30 19:54:22.719 OutlineView[10420:1613022] StringedText is 30 August 2014
2014-08-30 19:54:22.720 OutlineView[10420:1613022] label value is (null)
I include the following code:
//
// FirstViewContorller.h
// OutlineView
#import <Cocoa/Cocoa.h>
@interface FirstViewContorller : NSViewController
@property (weak) IBOutlet NSTextField *dateLabel;
-(void)updateDateScreen;
@end
//
// FirstViewContorller.m
// OutlineView
#import "FirstViewContorller.h"
@implementation FirstViewContorller
@synthesize dateLabel = _dateLabel;
-(void)updateDateScreen{
//date calculation for main window
NSDate *now = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterLongStyle];
NSString *stringedText = [formatter stringFromDate:now];
_dateLabel.stringValue = stringedText;
NSLog(@"StringedText is %@", stringedText);
NSLog(@"label value is %@", _dateLabel.value);
}
@end
//
// AppDelegate.m
// OutlineView
#import "AppDelegate.h"
#import "Book.h"
#import "FirstViewContorller.h"
@interface AppDelegate()
@property (weak) IBOutlet NSOutlineView *outlineView;
@property (weak) IBOutlet NSTreeController *booksController;
@end
@implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
//other code here
//Call the update method in FirstViewController to load date label
FirstViewContorller *instance = [[FirstViewContorller alloc]init];
[instance updateDateScreen];
}
//further unrelated code
@end
You have:
NSLog(@"label value is %@", _dateLabel.value);
And because it is outputting "null" you think that your value
is "null" when in all likelihood it is _dateLabel
that is null.
You are creating the instance
object, but then calling a method that updates a UI object, which may not have been unarchived from the xib file by the time you are calling it. So although your date formatter is correctly creating a string, it is trying to set it on a nil object.
You can see this for yourself by examining the output of of:
NSLog(@"label is %@", _dateLabel);
which will probably return a "null" as well.