Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does respondsToSelector not work for me in this case?

I have a little conundrum that is driving me right up the wall. I am using delegation pretty heavily as a pattern in an application I am writing. I'm trying to be as "careful" in the code calling the delegate as I can by testing the delegate with "[delegate respondsToSelector]" on each delegated call. Everything works fine unless I am in a UIView subclass. In that case, respondsToSelector returns NO yet I can safely call the delegate code so clearly it exists and works correctly.

I have boiled it down to the most simple example I can below. Any help you can provide would be appreciated:

Inside of my UIView subclass's .h file:

#import <UIKit/UIKit.h>

@protocol TestDelegate <NSObject>
@optional
-(double)GetLineWidth;
@end

@interface ViewSubclass : UIView {
    id<TestDelegate> delegate;
}

@property (nonatomic, retain) id<TestDelegate> delegate;

@end

Inside my delegate class's .h file:

#import <Foundation/Foundation.h>
#import "ViewSubclass.h"

@interface ViewDelegate : NSObject <TestDelegate> {

}

@end

Inside my delegate class's .m file:

#import "ViewDelegate.h"

@implementation ViewDelegate

-(double)GetLineWidth {
    return 25.0;
}

@end

Inside my UIView subclass's .m file:

- (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);
like image 807
user704315 Avatar asked Aug 31 '11 12:08

user704315


2 Answers

the selector for -(double)GetLineWidth is @selector(GetLineWidth).

you have an extra colon in your selector.

if ([delegate respondsToSelector:@selector(GetLineWidth:)]) {
                                                       ^
like image 172
Matthias Bauch Avatar answered Nov 03 '22 07:11

Matthias Bauch


Replace if-statement with this one:

if ([delegate respondsToSelector:@selector(GetLineWidth)]) {
    lineWidth = [delegate GetLineWidth];
}
like image 43
Nekto Avatar answered Nov 03 '22 08:11

Nekto