2012-08-10 113 views
1

我創建了一個簡單的可可應用程序。在MainMenu.xib中,我添加了一個NSDatePicker和一個NSTextField。這兩個對象都具有綁定到App Delegate屬性的值。我期望當用戶在NSDatePicker中更改日期時,NSTextField將被更新。這沒有發生。這是在App代表:如何註冊相關密鑰? (鍵值觀察)

// AppDelegate.h 
#import <Cocoa/Cocoa.h> 

@interface AppDelegate : NSObject <NSApplicationDelegate> 

@property (assign) IBOutlet NSWindow *window; 
@property (nonatomic, strong) NSDate *dateFromPicker; 
@property (nonatomic, readonly) NSString *dateString; 

@end 


// AppDelegate.m 
#import "AppDelegate.h" 

@implementation AppDelegate 

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification 
{ 

} 

- (NSString *)dateString 
{ 
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
    return [formatter stringFromDate:self.dateFromPicker]; 
} 

+ (NSSet *)keyPathsForValuesAffectingDateString 
{ 
    return [NSSet setWithObject:@"dateFromPicker"]; 
} 

@end 

更新代碼與dateFromPicker觀察員和一些的NSLog聲明:

@implementation AppDelegate 

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification 
{ 
    [self addObserver:self forKeyPath:@"dateFromPicker" options:0 context:NULL]; 
    self.dateFromPicker = [NSDate dateWithNaturalLanguageString:@"12/12/12"]; 
} 

- (NSString *)dateString 
{ 
    NSLog(@"dateString was called."); 
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
    return [formatter stringFromDate:self.dateFromPicker]; 
} 

+ (NSSet *)keyPathsForValuesAffectingDateString 
{ 
    NSLog(@"keyPathsForValuesAffectingDateString was called."); 
    return [NSSet setWithObject:@"dateFromPicker"]; 
} 

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:   (NSDictionary *)change context:(void *)context 
{ 
    NSLog(@"dateFromPicker changed."); 
} 

@end 

這裏是日誌:

2012-08-10 15:37:15.086 ... keyPathsForValuesAffectingDateString was called. 
2012-08-10 15:37:15.087 ... dateString was called. 
2012-08-10 15:37:15.116 ... dateFromPicker changed. 
2012-08-10 15:37:15.117 ... dateString was called. 
2012-08-10 15:37:19.831 ... dateFromPicker changed. 
2012-08-10 15:37:19.831 ... dateString was called. 
+0

我發現上面的代碼工作正常,直到它被放在NSArrayController的子類中。那是它最初在我的項目中的地方,但我創建了一個簡單的項目來解決這個問題。所以必須有一些關於影響KVO的NSArrayController類。 – 2012-08-11 02:28:51

回答

0

我知道這是不完全你在問什麼,但...

爲什麼你不把NSTextField綁定到NSDate屬性a nd在Interface Builder中添加一個格式化程序?

+0

這會工作,但我真的想更好地理解依賴鍵。我創建了這個例子來作爲提問的方式,並希望得到解釋爲什麼這不起作用。 – 2012-08-10 21:44:46

+0

好吧,我在代碼中看不到任何可疑的東西。嘗試設置一個觀察者,看看它是否觸發(如果是這樣,它與綁定有關,而不是KVO)。還要嘗試更改代碼中的日期,而不是使用選取器並查看它是否觸發。也可以添加一些打印輸出到日誌中,以便跟蹤發生什麼情況。 – 2012-08-10 22:20:01