我真的很难弄清楚为什么我的一个委托方法表现完美,但另一个不会。以下是代理的相关代码:
SideBarController.h
#import <UIKit/UIKit.h>
#import "Report.h"
@protocol ReportSelectViewControllerDelegate <NSObject>
@optional
- (void) viewSelectMonitoredArea:(Report *)report;
@end
@interface SidebarController : UIViewController <UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, weak) id <ReportSelectViewControllerDelegate> delegate;
@property (nonatomic, weak) IBOutlet UITableView *tableView;
@property (nonatomic, weak) Report *selectedReport;
@end
SideBarController.m
#import "SidebarController.h"
@interface SidebarController ()
@end
@implementation SidebarController
@synthesize tableView = _tableView;
@synthesize delegate;
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSMutableArray *sectionArray = [self.tableViewItems objectAtIndex:indexPath.section];
NSDictionary* item = sectionArray[indexPath.row];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:item[@"title"] forKey:@"CurrentReportTitle"];
self.selectedReport = [Report where:@{@"reportTitle": item[@"title"]}].lastObject;
[self.delegate viewSelectMonitoredArea:self.selectedReport];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
DetailReportViewController.h
#import <UIKit/UIKit.h>
#import "BDBSplitViewController.h"
#import "SidebarController.h"
@interface DetailReportViewController : BDBDetailViewController <UISplitViewControllerDelegate, ReportSelectViewControllerDelegate >
@end
DetailReportViewController.m
#import "DetailReportViewController.h"
@interface DetailReportViewController ()
@end
@implementation DetailReportViewController
- (void)viewDidLoad
{
[super viewDidLoad];
SidebarController *sideBarController = [[SidebarController alloc] init];
sideBarController.delegate = self;
}
- (void) viewSelectMonitoredArea:(Report *)report {
NSLog(@"viewSelectMonitoredArea was called");
}
从另一个控制器到DetailReportViewController以完全相同的方式编写的另一个委托工作正常。当我在调用委托后立即设置断点时,我注意到委托的值为nil。任何帮助将不胜感激。
修改
抱歉,我忘记在DetailReportViewController.h示例中输入sideBarController.delegate = self
。它在原始代码中。
答案 0 :(得分:1)
DetailReportViewController类需要获取对“SideBarController”实例的引用,然后将自己设置为委托。在DetailReportViewController中:
// This needs to be in the DetailReportViewController class
// Assume we have a reference to the SideBarController in the DetailReportViewController class called sideBarControllerInstance
sideBarControllerInstance.delegate = self;
答案 1 :(得分:1)
迈克尔·道特曼推动的解决方案是
DetailReportViewController *detailReport = [[DetailReportViewController alloc] init];
self.delegate = detailReport;
之前
[self.delegate createSelectMonitoredArea:self.selectedReport];
谢谢!