monteiro_luiz monteiro_luiz - 5 months ago 24
iOS Question

Protocol does respondsToSelector not work for me in this case?

I have a problem to create a protocol the respondsToSelector not calling the method. Maybe someone can see where I'm going wrong.

See my code:

Protocol.h


#import <UIKit/UIKit.h>
@protocol CHTumblrMenuDelegate <NSObject>
@required
- (void)dismissView;
@end

typedef void (^CHTumblrMenuViewSelectedBlock)(void);

@interface CHTumblrMenuView : UIView<UIGestureRecognizerDelegate,CHTumblrMenuDelegate>{
id<CHTumblrMenuDelegate>delegate;
}

@property (nonatomic, weak) id<CHTumblrMenuDelegate> delegate;


Protocol.m


- (id)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
UITapGestureRecognizer *ges = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismiss:)];
ges.delegate = self;
[self addGestureRecognizer:ges];
self.backgroundColor = [UIColor clearColor];
backgroundView_ = [[UIImageView alloc] initWithFrame:self.bounds];
//backgroundView_.backgroundColor = TumblrBlue;
backgroundView_.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;

UIGraphicsBeginImageContext(backgroundView_.frame.size);
[[UIImage imageNamed:@"background"] drawInRect:backgroundView_.bounds];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
backgroundView_.backgroundColor = [UIColor colorWithPatternImage:image];

[self addSubview:backgroundView_];
buttons_ = [[NSMutableArray alloc] initWithCapacity:6];


}
return self;
}

- (void)dismiss:(id)sender{
NSLog(@"DIS");

if (delegate == nil) {
CHTumblrMenuView *vd = [[CHTumblrMenuView alloc]init];
delegate = vd;
}
[delegate respondsToSelector:@selector(dismissView)];

[self dropAnimation];
double delayInSeconds = CHTumblrMenuViewAnimationTime + CHTumblrMenuViewAnimationInterval * (buttons_.count + 1);
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){

[self removeFromSuperview];
});
}


ClassUseProtocol.m


CHTumblrMenuView *menuView = [[CHTumblrMenuView alloc] init];
menuView.delegate = self;

-(void)dismissView{
NSLog(@"DismissView");
}


Log:
2016-06-06 22:44:07.258 ProtocolExample[7513:4030481] DIS


does anyone have any idea what might be going on?

Answer

Your protocol method is @required, So no need to check for

 delegate respondsToSelector:@selector(dismissView)

In case of un-define dismissView method, you will got compile time error.You can below line

 if (self.delegate && [self.delegate conformsToProtocol:@protocol(CHTumblrMenuDelegate)]) {
    [self.delegate dismissView];
 }