如何正确执行委派? [英] How to implement delegation the right way?

查看:50
本文介绍了如何正确执行委派?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为发生特殊情况的类实现委托,该类应称为委托(如果有的话).

I'm trying to implement delegation for a class which should call it's delegate (if any), when special things happen.

在Wikipedia中,我有以下代码示例:

From Wikipedia I have this code example:

 @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

如果我自己尝试此操作,则会收到一条警告,指出未找到我在委托上调用的方法.当然不是,因为该委托仅由id引用.可能是任何东西.确保在运行时可以正常工作,因为我检查了它是否对选择器作出响应.但是我不想要Xcode中的警告.有更好的模式吗?

If I try this on my own, I get a warning that the method I am calling on the delegate was not found. Of course it was not, because the delegate is just referenced by id. It could be anything. Sure at runtime that will work fine because I check if it responds to selector. But I don't want the warning in Xcode. Are there better patterns?

推荐答案

您可以让委托具有实现SomeClassDelegate协议的id类型.为此,您可以在SomeClass的标题(以您的情况为TCScrollView)中,执行以下操作:

You could let the delegate be of the id type that implements the SomeClassDelegate protocol. For this, you could in the header of your SomeClass (in your case TCScrollView), do something like this:

@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

然后您可以从实现中调用代理上的方法:

Then you can from your implementation, just call the method on the delegate:

@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

这篇关于如何正确执行委派?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆