2014-07-24 67 views
-2

使用协议和委托不是我经常使用的东西(我之前使用过),但是这一次,我做了所有事情,因为它应该完成,但协议的方法没有被调用。为什么不调用这个委托方法?

所以我有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)子视图连接: enter image description here 的有趣之处在于当按钮被按下时,如果返回false。 有没有人可以解释为什么会发生这种情况? 谢谢

+0

你能检查'self.delegate'是否在按钮点击处理程序中为零吗? – Macondo2Seattle

+0

是的,它是零。但我不明白为什么 – user1792771

+0

我检查,如果对象toolBarViewController是零后,我在core.m中设置委托,它不为空。那么为什么ToolBarViewController中的委托是零? – user1792771

回答

0

此行创建一个全新的视图控制器。它确实而不是获得已经在您的视图层次结构中的那个。

toolBarViewController = [[ToolBarViewController alloc] init]; 

如果ToolBarViewController已经在你的视图层次结构中,你应该这样做。

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    [self.toolBarViewController setDelegate:self]; 
} 

如果它不您的视图层次的是,它应该是这个样子。

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    self.toolBarViewController = [[ToolBarViewController alloc] init]; 
    [self.toolBarViewController setDelegate:self]; 
    [self.view addSubview:self.toolBarViewController.view]; 
} 
+0

问题是,toolBarViewController在Core.h中声明为强属性,并且在您突出显示的行中第一次初始化。如果我删除该行,那么toolBarViewObject将不会被初始化 – user1792771

+1

ToolBarViewController如何进入视图层次结构?它在哪里呈现? – CrimsonChris

+0

程序结构是:appdelegate声明并创建核心对象,核心类声明并创建toolbarviewcontroller和mainviewcontroller。 toolbarviewcontroller和mainviewcontroller在应用程序的主窗口中控制2个子视图 – user1792771

相关问题