1

我创建了一个简单的 Cocoa 应用程序。在 MainMenu.xib 我添加了一个 NSDatePicker 和一个 NSTextField。这两个对象都有到 App Delegate 属性的值绑定。我希望当用户更改 NSDatePicker 中的日期时,将更新 NSTextField。这不会发生。这是应用程序代表:

//  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.
4

1 回答 1

0

我知道这不是您要问的,但是...

为什么不将 NSTextField 绑定到 NSDate 属性并在 Interface Builder 中为其添加格式化程序?

于 2012-08-10T21:38:44.530 回答