我已经阅读过,而且好像代表会在我的应用中真正有用。不幸的是,关于我尝试过的协议的每个教程都失败了 - 代表没有收到消息!如果有人能告诉我我做错了什么,那将会很棒。Objective-C协议不发送消息
我用两个ViewControllers,一个FirstViewController和一个SecondViewController创建了一个非常简单的测试应用程序。我已经在容器视图中设置它们以正确查看效果。 我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];
}
我想我已经实现的协议和委托的正确调用。
这里是我的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;
}
我已经breakpointed该项目,并意识到colourDidChange:
在SecondViewController永远不会执行。 如果有人能够指出我做错了什么,是否宣布(或遵守)代表不力,或者不是以正确的方式设置代表,我们将不胜感激。
非常感谢。
你断点在哪里? In-colourDidChange:?或者在 - 被压制/ -bluePressed?这可能有助于确定事情发生的地方,例如如果在行动中,或许代表是零,为什么事情没有进展。我可以看到一些错误:1.委托属性是一个弱财产('弱'或'分配'),而不是保留/强。另外,IBAction的签名应该是 - (IBAction):foo:(id)sender;你的行为缺乏'身份证'的论点。 – hsoi
我突出了两个 - 当调用blue/redPressed时,self.delegate是0x0。从另一个类设置变量从来没有为我工作。 – nanothread59
好的。我的猜测是你可能有2个FirstViewController实例,特别是因为在你的SectionViewController中创建的'firstView'不一定是以一种典型的方式创建的。由于您使用的是故事板,因此您可以尝试将代理作为IBOutlet公开,并将其连接到故事板而不是-viewDidLoad中。 – hsoi