【发布时间】:2010-11-16 10:16:20
【问题描述】:
我正在尝试为一个应该称为委托(如果有的话)的类实现委托,当特殊情况发生时。
来自维基百科我有这个代码示例:
@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 中的警告。有更好的模式吗?
【问题讨论】:
-
您不必在 Objective-c 中检查 nil。向 nil 对象发送消息是合法的。
-
在这种情况下,您不需要检查 nil,因为 BOOL 小于 sizeof(void*)。然而,对于任何其他大小的返回类型——比如说,一个大型结构——返回值是未定义的,因此,检查 nil 是防止未定义行为的唯一方法。
标签: iphone delegation