2014-08-30 47 views
0

我遇到了標籤問題,未在我的用戶界面中正確更新。我有一個使用大綱視圖切換視圖的Mac OS X應用程序。我只想在切換到(FirstViewController)的視圖上的標籤上顯示給用戶的日期。當在一個新項目中單獨實施時,我沒有問題。但是,如果在視圖更改的地方實現,標籤的值不會更新,事實上,即使先前設置了控制檯輸出,也表明_dateLabel爲(null)。有什麼建議麼?我必須錯過一些非常基礎的東西!標籤更新爲空

控制檯輸出:

2014年8月30日19:54:22.719 OutlineView [10420:1613022] StringedText是2014年8月30

2014年8月30日19:54:22.720 OutlineView [10420: 1613022]標籤值(NULL)

我包括下面的代碼:

// 
// 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 
+0

您必須等到viewDidLoad或viewWillAppear才能更新UI對象,因爲它們在視圖加載之前不存在。而且您還需要確保UI對象正確鏈接到XIB中的類。 – 2014-08-30 13:25:43

回答

1

您有:

NSLog(@"label value is %@", _dateLabel.value); 

因爲它是輸出「空」你認爲你的value爲「null」時,十有八九是_dateLabel是空。

您正在創建instance對象,但隨後調用更新UI對象的方法,該對象在您調用它時可能尚未從xib文件中取消存檔。因此,雖然日期格式化程序正確地創建了一個字符串,但它試圖將它設置爲一個零對象。

可以通過檢查的輸出看到自己這一點:

NSLog(@"label is %@", _dateLabel); 

這可能會返回一個「空」的可能。

+0

謝謝Abizern--這讓你很有意義。那麼我該如何去更新方法中的標籤呢?我不能直接從appDelegate調用它,所以我認爲我只能從與XIB相關的類中調用它。 – user3932488 2014-08-30 11:20:48

+0

該單元格僅在視圖加載後出現。所以在視圖加載時或在'awakeFromNib'時調用它。 – Abizern 2014-08-30 13:48:16

+0

謝謝,解決了這個問題。我只是將我的代碼移到了awakeFromNib方法中,現在它工作正常。我以爲我最初在那裏有代碼,但沒有被調用 - 爲什麼我創建了新的方法,但它現在正在工作。非常感謝你的幫助。 – user3932488 2014-08-30 21:04:09