我正在尝试为一个应该调用它的委托(如果有的话)的类实现委托,当特殊事情发生时.
从维基百科我有这个代码示例:
@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
Run Code Online (Sandbox Code Playgroud)
如果我自己尝试这个,我会收到一个警告,说我找不到我在代理上调用的方法.当然不是,因为委托只是由id引用.它可能是任何东西.当然在运行时会工作正常,因为我检查它是否响应选择器.但我不想在Xcode中发出警告.有更好的模式吗?
您可以让委托者具有实现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
Run Code Online (Sandbox Code Playgroud)
然后你可以从你的实现中,只需调用委托上的方法:
@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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
935 次 |
| 最近记录: |