我试图实现的代表团一类,它应该叫它的代表(如果有的话),当特别的事情发生。

从维基百科的我有这个代码的例子:

 @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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top