使用协议和委托不是我经常使用的东西(我之前使用过),但是这一次,我做了所有事情,因为它应该完成,但协议的方法没有被调用。为什么不调用这个委托方法?
所以我有2个类:ToolBarViewController和核心,并在ToolBarView我有1个按钮。当我按下按钮时,它应该调用从ToolBarViewControllerDelegate按下的方法toolBarButton。 一些代码:
1)协议和委托声明在ToolBarViewController.h
@protocol ToolBarViewControllerDelegate <NSObject>
@optional
-(void)toolBarButtonPressed:(NSString*)buttonName;
@end
。 。
@property (nonatomic, weak) id<ToolBarViewControllerDelegate> delegate;
2)在ToolBarViewController.m方法呼叫
- (IBAction)button1:(NSButton *)sender {
NSLog(@"b1");
if([ self.delegate respondsToSelector:@selector(toolBarButtonPressed:)]){
[self.delegate toolBarButtonPressed:@"button1"];
}else{
NSLog(@"don't responde");
}
}
3)在Core.h
@interface Core : NSObject<ToolBarViewControllerDelegate>
4使用ToolVarViewControllerDelegate核心)实例化对象ToolBarViewController和在设置代表Core.m
-(id)init{
self = [super init];
if (self){
toolBarViewController = [[ToolBarViewController alloc]init];
[toolBarViewController setDelegate:self];
self.mainViewController = [[MainViewController alloc]init];
NSLog(@"Core Inited.........DONE");
}
return self;
} 5)的方法,toolBarButtonPressed:在Core.m
-(void)toolBarButtonPressed:(NSString*)buttonName{
NSLog(@"Button pressed %@",buttonName);
}
6)ToolBarViewController声明在core.h:
@property (strong) ToolBarViewController* toolBarViewController;
7)子视图连接: 的有趣之处在于当按钮被按下时,如果返回false。 有没有人可以解释为什么会发生这种情况? 谢谢
你能检查'self.delegate'是否在按钮点击处理程序中为零吗? – Macondo2Seattle
是的,它是零。但我不明白为什么 – user1792771
我检查,如果对象toolBarViewController是零后,我在core.m中设置委托,它不为空。那么为什么ToolBarViewController中的委托是零? – user1792771