为什么respondsToSelector不为我在这种情况下工作



我有一个小难题,把我逼疯了。我在编写的应用程序中大量使用委托作为模式。我试图在调用委托的代码中"小心",因为我可以通过在每个委托调用上测试带有"[delegate respondsToSelector]"的委托。一切都很好,除非我在UIView子类中。在这种情况下,respondsToSelector返回NO,但我可以安全地调用委托代码,所以它清楚地存在并正确工作。

我已经把它归结为下面最简单的例子。如果您能提供任何帮助,我将不胜感激:

在我的UIView子类的。h文件中:

#import <UIKit/UIKit.h>
@protocol TestDelegate <NSObject>
@optional
-(double)GetLineWidth;
@end
@interface ViewSubclass : UIView {
    id<TestDelegate> delegate;
}
@property (nonatomic, retain) id<TestDelegate> delegate;
@end

在我的委托类的。h文件中:

#import <Foundation/Foundation.h>
#import "ViewSubclass.h"
@interface ViewDelegate : NSObject <TestDelegate> {
}
@end

在我的委托类的。m文件中:

#import "ViewDelegate.h"
@implementation ViewDelegate
-(double)GetLineWidth {
    return 25.0;
}
@end

在我的UIView子类的。m文件中:

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    double lineWidth = 2.0;
    if (delegate == nil) {
        ViewDelegate *vd = [[ViewDelegate alloc]init];
        delegate = vd;
    }
    // If I comment out the "if" statement and just call the delegate
    // delegate directly, the call works!
    if ([delegate respondsToSelector:@selector(GetLineWidth:)]) {
        lineWidth = [delegate GetLineWidth];
    }
    CGContextSetLineWidth(context, lineWidth);

-(double)GetLineWidth的选择器为@selector(GetLineWidth)

选择器中有一个额外的冒号。

if ([delegate respondsToSelector:@selector(GetLineWidth:)]) {
                                                       ^

if-statement替换为以下语句:

if ([delegate respondsToSelector:@selector(GetLineWidth)]) {
    lineWidth = [delegate GetLineWidth];
}

最新更新