我在 .h 文件中声明了一个名为 dateSelectViewController 的方法作为协议(protocol):
@class DateSelectViewController;
@protocol DateSelectViewControllerDelegate
- (void)dateSelectViewController:(DateSelectViewController *)sender
theDate:(id)stringDate;
@end
在协议(protocol)下方,我声明了一个委托(delegate):
@property (nonatomic, weak) id <DateSelectViewControllerDelegate> delegate;
在实现文件中,我合成了委托(delegate),并在我的 View 中按下完成按钮时向委托(delegate)发送消息:
- (IBAction)DonePressed:(id)sender {
NSDate *chosen = [datePicker date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MM/dd/yyyy"];
NSString *formatedDate = [formatter stringFromDate:chosen];
//sending a message to the delegate
[self.delegate dateSelectViewController:self theDate:formatedDate];
[self.navigationController popViewControllerAnimated:YES];
}
在被委托(delegate)的 .h 文件中,我正在导入委托(delegate)人 .h 文件。在 .m 文件中,我符合协议(protocol):
@interface MakePlantTVC ()<DateSelectViewControllerDelegate>
- (void)dateSelectViewController:(DateSelectViewController *)sender
theDate:(id)stringDate
{
self.displayDate.text = stringDate;
NSLog(@"delegate working");
}
出于某种原因,这完全有效。当在我的委托(delegate)类中按下完成按钮时,该按钮会按预期方式执行并弹出 View Controller ,但就像消息从未发送给委托(delegate)一样。起初我以为我可以向 nil 发送一条消息,但它的类型为 id,所以情况不应该如此。为什么消息没有被发送?
最佳答案
想到了一些事情
- 你设置委托(delegate)了吗?这听起来可能很愚蠢,但当委托(delegate)不工作时,90% 的情况是因为我忘记或失去了 IB 连接。
- 你的弱对象会过期吗?一个弱对象被 nil'ed - 因此你正在对“无”执行委托(delegate)操作 - 也许你想要更多的保留或
NSNotification
我与委托(delegate)一起练习的其他可能有用的事情
- 使用基于断言的编程?当你有一个具有所需功能的协议(protocol)时,值得断言,即:
NSAssert(delegate, @"Error, delegate not set!");
- 检查代理是否响应选择器
使用 GCD 异步调度委托(delegate)调用,即:
dispatch_async(dispatch_get_main_queue(), ^{ if ([delegate_ respondsToSelector:@selector(updateUI:)]) [delegate_ updateUI:self]; });
希望这对您有所帮助!
关于objective-c - 为什么这个委托(delegate) - 协议(protocol)没有响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10315800/