我正在努力学习可可,我不确定我是否正确地理解了这一点.它是关于委托、和控制器的。
首先:这两者有什么区别?有时,我看到一个类名为AppController的代码,有时--内容大致相同-- AppDelegate。
因此,如果我正确理解它,委托就是一个简单的对象,当某个事件发生时,它接收消息。例如:
@interface WindowController : NSObject <NSWindowDelegate>
@end
@implementation WindowController
- (void)windowDidMiniaturize:(NSNotification *)notification {
NSLog(@"-windowDidMiniaturize");
}
@end现在,我使用这段代码使它成为我的window的委托
@interface TryingAppDelegate : NSObject <NSApplicationDelegate> {
NSWindow *window;
}
@property (assign) IBOutlet NSWindow *window;
@property (retain) WindowController *winController;
@end执行如下:
@implementation TryingAppDelegate
@synthesize window;
@synthesize winController;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
NSLog(@"-applicationDidFinishLaunching:");
self.winController = [[WindowController alloc] init];
[window setDelegate:winController];
[self.winController release];
}
@end现在,每当我最小化window时,它就会向WindowController发送一条-windowDidMiniaturize:消息。我有这个权利吗?
如果是这样的话,为什么不直接使用子类NSWindow,而不需要处理一个额外的类呢?
发布于 2011-10-07 11:27:10
当您希望一个对象协调其他几个对象时,委托特别有用。例如,您可以创建一个NSWindowController子类并使其成为窗口的委托。该窗口可能包含其他几个元素(如NSTextFields),您希望使窗口控制器成为其委托。这样,您就不需要对窗口及其几个控件进行子类化。您可以将概念上属于同一类的所有代码保存在一起。此外,委托通常属于模型-视图-控制器概念的控制器级别.通过子类NSWindow,您可以将控制器类型代码移动到视图级别。
类可以采用任意数量的协议,因此<NSWindowDelegate, NSTextFieldDelegate>是完全有效的。然后,可以将对象设置为任意数量的窗口和文本字段的委托。要了解像NSTextField这样的类所支持的委托消息,请查看class reference、.The、-delegate和-setDelegate:方法,这些方法通常会指向正确的协议。在我们的例子中,这是NSTextFieldDelegate。对于已经添加到较早版本的Apple框架中的类,通常会增加一个关于委托方法的部分(或者与“类方法”和“实例方法”一起使用,或者作为“任务”的一个小节)。请注意,声明您的类符合委托协议不会让它们神奇地传递到对象-您必须显式地将其设置为委托:
@interface MyWindowController : NSWindowController <NSWindowDelegate, NSTextFieldDelegate> {
NSTextField *_someTextField;
}
@property (nonatomic, retain) IBOutlet NSTextField *someTextField;
@end
@implementation MyWindowController
@synthesize someTextField = _someTextField;
- (void)dealloc {
[_someTextField release];
[super dealloc];
}
- (void)windowDidLoad {
[super windowDidLoad];
// When using a XIB/NIB, you can also set the File's Owner as the
// delegate of the window and the text field.
[[self window] setDelegate:self];
[[self someTextField] setDelegate:self];
}
- (void)windowDidMiniaturize:(NSNotification *)notification {
}
- (BOOL)control:(NSControl *)control textShouldEndEditing:(NSText *)fieldEditor {
return YES;
}
@endAppController和AppDelegate只是同一类型类的不同命名约定。
https://stackoverflow.com/questions/7686202
复制相似问题