我已经阅读了周围的内容,似乎委托(delegate)在我的应用程序中非常有用。不幸的是,我尝试过的每个关于协议(protocol)的教程都失败了——委托(delegate)人没有收到消息!如果有人能告诉我我做错了什么,那就太好了。
我创建了一个非常简单的测试应用程序,其中包含两个 ViewController,一个 FirstViewController 和一个 SecondViewController。我已将它们设置在容器 View 中以正确查看效果。 我的 Main.storyboard 看起来像这样:
测试应用程序的目的是当在 FirstViewController 中按下其中一个按钮时更改 SecondViewController 的背景颜色。
这是 FirstViewController.h:
#import <UIKit/UIKit.h>
@protocol FirstViewControllerDelegate
-(void)colourDidChange:(UIColor *)theColour;
@end
@interface FirstViewController : UIViewController{
UIButton *redButton;
UIButton *blueButton;
}
@property (nonatomic, retain) id <FirstViewControllerDelegate> delegate;
@property (nonatomic, retain) IBOutlet UIButton *redButton;
@property (nonatomic, retain) IBOutlet UIButton *blueButton;
-(IBAction)redPressed;
-(IBAction)bluePressed;
我的FirstViewController.m:
#import "FirstViewController.h"
@interface FirstViewController ()
@end
@implementation FirstViewController
@synthesize redButton, blueButton;
@synthesize delegate;
-(IBAction)redPressed{
[self.delegate colourDidChange:[UIColor redColor]];
}
-(IBAction)bluePressed{
[self.delegate colourDidChange:[UIColor blueColor]];
}
-(void)viewDidLoad
{
[super viewDidLoad];
}
我认为我已经正确实现了协议(protocol)和委托(delegate)的调用。
这是我的 SecondViewController.h:
#import <UIKit/UIKit.h>
#import "FirstViewController.h"
@interface SecondViewController : UIViewController <FirstViewControllerDelegate>
-(void)colourDidChange:(UIColor *)theColour;
还有我的 SecondViewController.m:
-(void)colourDidChange:(UIColor *)theColour{
self.view.backgroundColor = theColour;
}
-(void)viewDidLoad
{
[super viewDidLoad];
FirstViewController *firstView = [[FirstViewController alloc]init];
firstView.delegate = self;
}
我已经对项目进行了断点,并意识到 SecondViewController 中的 colourDidChange:
永远不会执行。
如果有人能指出我做错了什么,无论是声明(或遵守)委托(delegate)不当还是没有以正确的方式设置委托(delegate),我将不胜感激。
非常感谢。
最佳答案
我怀疑有 2 个 FirstViewController
实例,一个是由 Storyboard 创建的,另一个是在 SecondViewController
的 viewDidLoad
方法中创建的。
当FirstViewController
创建SecondViewController
时,它可以设置委托(delegate)属性或使用Outlet来连接它们。
注意:委托(delegate)属性不应该是retain
,而应该是assign
(或者使用ARC时weak
)。
关于Objective-C 协议(protocol)不发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20455595/