我有一個問題來創建一個協議的respondsToSelector不調用該方法。也許有人可以看到我要去哪裏錯了。Protocol在這種情況下,respondsToSelector不適用於我嗎?
見我的代碼:
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");
}
日誌: 2016-06-06 22:44:07.258 ProtocolExample[7513:4030481] DIS
有沒有人有任何想法可能會發生什麼?
此答案中的'if'語句沒有任何意義。你爲什麼要檢查'self'是否符合協議?沒有任何理由說明爲什麼「自我」符合協議。這是代表需要遵守協議的代表。它是需要實現協議方法的委託。 – rmaddy
我使代碼更通用,協議/委託在VC之間有1對1的關係,所以如果你的設計具有VC層次結構級別,則條件是有條件的。 – kaushal
你說什麼沒有任何意義。它是符合協議的代表,而不是具有'delegate'屬性的類。在你的答案中的代碼中,'self'不應該符合協議。只有'self.delegate'應符合協議。 – rmaddy