我使用这个类:
<>之前
@interface NSObject( WiiRemoteDiscoveryDelegate )
- (void) WiiRemoteDiscovered:(WiiRemote*)wiimote;
- (void) WiiRemoteDiscoveryError:(int)code;
@end;
之前但是我如何子类化这个呢?
这被称为非正式协议,在最近的Mac OS x版本之前,Cocoa框架主要是这样声明委托方法的。
这段代码只是说它将在某些对象上调用方法"WiiRemoteDiscovered:"one_answers"WiiRemoteDiscoveryError:"。类别的名称"WiiRemoteDiscoveryDelegate"表明它计划在委托上调用这些方法。
想象一些像这样的代码:
@interface WiiRemoteDiscoverer {
id delegate;
}
@property id delegate;
- (void)startDiscovery;
@end
@implementation WiiRemoteDiscoverer
@synthesize delegate;
- (void)startDiscovery {
/* do the discovery ... */
[delegate WiiRemoteDiscoveryError:-1];
}
@end
如果你要构建它,你会在调用WiiRemoteDiscoveryError:的行上得到一个编译器警告,因为该方法没有在任何地方声明。为了避免这种情况,你可以做两件事之一。您可以像该类的作者所做的那样,将其添加到头文件中:
@interface NSObject( WiiRemoteDiscoveryDelegate )
- (void) WiiRemoteDiscovered:(WiiRemote*)wiimote;
- (void) WiiRemoteDiscoveryError:(int)code;
@end;
该块基本上是说每个对象实现WiiRemoteDiscovered:(这不是真的),并沉默编译器警告。
或者你可以写得更正式一些,像这样:
@protocol WiiRemoteDiscovererDelegate <NSObject>
- (id)wiiRemoteDiscoveryError:(int)errorCode;
@end
@interface WiiRemoteDiscoverer {
id <WiiRemoteDiscovererDelegate> delegate;
}
@property id <WiiRemoteDiscovererDelegate> delegate;
- (void)startDiscovery;
@end
@implementation WiiRemoteDiscoverer
@synthesize delegate;
- (void)startDiscovery {
/* do the discovery ... */
[delegate wiiRemoteDiscoveryError:-1];
}
@end