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