Objective-C 协议(protocol)不发送消息

标签 objective-c cocoa-touch delegates protocols

我已经阅读了周围的内容,似乎委托(delegate)在我的应用程序中非常有用。不幸的是,我尝试过的每个关于协议(protocol)的教程都失败了——委托(delegate)人没有收到消息!如果有人能告诉我我做错了什么,那就太好了。

我创建了一个非常简单的测试应用程序,其中包含两个 ViewController,一个 FirstViewController 和一个 SecondViewController。我已将它们设置在容器 View 中以正确查看效果。 我的 Main.storyboard 看起来像这样:

Main.storybord

测试应用程序的目的是当在 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 创建的,另一个是在 SecondViewControllerviewDidLoad 方法中创建的。

FirstViewController创建SecondViewController时,它可以设置委托(delegate)属性或使用Outlet来连接它们。

注意:委托(delegate)属性不应该是retain,而应该是assign(或者使用ARC时weak)。

关于Objective-C 协议(protocol)不发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20455595/

相关文章:

iphone - UINavigationBar 标题标签文字

ios - 我可以获得计算路线的路线位置数组(坐标)吗? (Skobbler map )

iphone - MacOS/iPhone库交叉编译的最佳实践

objective-c - 将正则表达式与字符串(文件名)匹配

iphone - 如何在 _NSLockError() 上设置断点

c# - 将 Func 委托(delegate)为属性

objective-c - 如何将 UIImage 从 iPhone 应用程序传递到 Apple Watch 应用程序

ios - RestKit 不喜欢为 POST 响应映射不同的对象

objective-c - 如何创建或分配委托(delegate)人?

java - 如何在 lucene 4.x 中正确实现委托(delegate)分词器?