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);
the selector for -(double)GetLineWidth
is @selector(GetLineWidth)
.
you have an extra colon in your selector.
if ([delegate respondsToSelector:@selector(GetLineWidth:)]) {
^
Replace if-statement with this one:
if ([delegate respondsToSelector:@selector(GetLineWidth)]) {
lineWidth = [delegate GetLineWidth];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With