执行代表团 [英] Implementing delegation
问题描述
我认为我正在关注代表团的工作原理,这里是我遵循的教程,但我在某个地方搞砸了。我期望我的委托给NSLog,但不是。谁能找出我失踪或做错了?
I think I'm following how delegation works, here's the tutorial I followed, but I'm messing up somewhere. I'm expecting my delegate to NSLog but it's not. Can anyone find out what am I missing or doing wrong?
我的 MainViewController.h :
@interface MainViewController : UITableViewController < AddClassDelegate >
MainViewController.m :
- (void)cancelAddingClass {
NSLog(@"Canceled Yo");
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
/*
When a row is selected, the segue creates the detail view controller as the destination.
Set the detail view controller's detail item to the item associated with the selected row.
*/
if ([[segue identifier] isEqualToString:@"addClassSegue"]) {
UINavigationController *nc = (UINavigationController *)segue.destinationViewController;
AddClassViewController *addClassVC = (AddClassViewController *)[nc.viewControllers objectAtIndex:0];
addClassVC.delegate = self;
}
我的模态视图控制器 AddClassViewController.h :
@protocol AddClassDelegate <NSObject>
- (void)cancelAddingClass;
@end
@interface AddClassViewController : UITableViewController
@property (weak, nonatomic) id< AddClassDelegate > delegate;
- (IBAction)cancelButtonPressed:(id)sender;
AddClassViewController.m :
@synthesize delegate;
- (IBAction)cancelButtonPressed:(id)sender {
[self.delegate cancelAddingClass];
}
cancelButtonPressed:
被连接到模态
推荐答案
你的代码看起来不错,这表明问题是我们看不到的地方。我的猜测在这里:
Your code looks fine, which suggests the problem is somewhere we can't see. My guess is here:
AddClassViewController *addClassVC = [segue destinationViewController];
addClassVC.delegate = self;
NSLog(@"segued");
您是否在导航控制器中嵌入了模态视图控制器?如果是这样,destinationViewController会给你导航控制器,而不是AddClassViewController。检查调试器中实际上是什么类的addClassVC。
Have you embedded your modal view controller in a navigation controller? If so, destinationViewController gives you the navigation controller, not the AddClassViewController. Check what class addClassVC actually is in the debugger.
如果是导航控制器,没问题,只需要使用 .viewController
财产。在几行中使它更容易理解:
If it is a navigation controller, no problem, you just need to get to your actual VC using the .viewControllers
property. On several lines to make it simpler to understand:
UINavigationController *nc = (UINavigationController *)segue.destinationViewController;
AddClassViewController *addClassVC = (AddClassViewController *)[nc.viewControllers objectAtIndex:0];
addClassVC.delegate = self;
你可以用更少的行来做,但它是一个混乱的铸造和嵌套的括号,这是更难调试
You can do it in fewer lines but it's a mess of casting and nested brackets, which is harder to debug.
这篇关于执行代表团的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!