题
我试图实现的代表团一类,它应该叫它的代表(如果有的话),当特别的事情发生。
从维基百科的我有这个代码的例子:
@implementation TCScrollView
-(void)scrollToPoint:(NSPoint)to;
{
BOOL shouldScroll = YES;
// If we have a delegate, and that delegate indeed does implement our delegate method,
if(delegate && [delegate respondsToSelector:@selector(scrollView:shouldScrollToPoint:)])
shouldScroll = [delegate scrollView:self shouldScrollToPoint:to]; // ask it if it's okay to scroll to this point.
if(!shouldScroll) return; // If not, ignore the scroll request.
/// Scrolling code omitted.
}
@end
如果我试试这个我自己的,我得到一个警告的方法,我呼吁代表没有被发现。当然不是,因为委托只是引用的标识。它可能是任何东西。肯定是在运行时,将正常工作,因为我检查,如果它响应选择。但我不想警告在载。是否有更好的模式?
解决方案
您可以让该委托是实现SomeClassDelegate协议ID类型的。对于这一点,你可以在你的SomeClass的的头(你的情况TCScrollView),做这样的事情:
@protocol TCScrollViewDelegate; // forward declaration of the protocol
@interface TCScrollView {
// ...
id <TCScrollViewDelegate> delegate;
}
@property (assign) id<TCScrollViewDelegate> delegate;
@end
@protocol TCScrollViewDelegate
- (BOOL) scrollView:(TCScrollView *)tcScrollView shouldScrollToPoint:(CGPoint)to;
@end
然后你可以从你的实现,只要调用方法的委托:
@implementation TCScrollView
-(void)scrollToPoint:(NSPoint)to;
{
BOOL shouldScroll = YES;
shouldScroll = [delegate scrollView:self shouldScrollToPoint:to]; // ask it if it's okay to scroll to this point.
if(!shouldScroll) return; // If not, ignore the scroll request.
/// Scrolling code omitted.
}
@end
其他提示
在 drvdijk的回答样本代码跟进一>,有可能是一个问题,如果有任何机会,delegate
可能是nil
当你调用委托方法。
发送到0.0
的消息的返回值是0
(又名NO
又名NSObject
又名respondsToSelector:
),所以如果是<=> <=>,
[delegate scrollView:self shouldScrollToPoint:to]
将返回<=>,这可能不是你的情况所需的行为。这是更安全的第一检查:
if (delegate != nil) {
shouldScroll = [delegate scrollView:self shouldScrollToPoint:to]
}
另外,如果你不想通过发送宣布<=>邮件到您的委托(如<=>)时,看到一个编译器警告,包括<=>协议在协议声明:
@protocol TScrollViewDelegate <NSObject>
- (BOOL) scrollView:(TCScrollView *)tcScrollView shouldScrollToPoint:(CGPoint)to;
@end
使用 [NSObject performSelector:]
[delegate performSelector:@selector(scrollView:shouldScrollToPoint:) withObject:self withObject:to];
你不会得到编译器的警告了
或者创建一个prototcol和声明 MyProtocol *delegate
在标题的文件。
不隶属于 StackOverflow