我想構建一個委託讓我將數據從一個子視圖控制器傳遞給父級。我一直在網上查看各種教程/問題,但我的委託方法沒有被觸發。爲什麼不是我的自定義代理工作?
你可以看看我的代碼在下面,看看我是否失去了什麼?
TownListViewController.h
@protocol TownListViewControllerDelegate;
@interface TownListViewController : UITableViewController <NSFetchedResultsControllerDelegate> {
id <TownListViewControllerDelegate> delegate;
}
@property (nonatomic, assign) id <TownListViewControllerDelegate> delegate;
@end
@protocol TownListViewControllerDelegate
@optional
- (void)didSelectTown:(Town *)town;
@end
TownListViewController.m
@implementation TownListViewController
@synthesize delegate;
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[delegate didSelectTown:(Town *)[self.fetchedResultsController objectAtIndexPath:indexPath]];
[self.navigationController popViewControllerAnimated:YES];
}
@end
SearchViewController.h
@interface SearchViewController : UITableViewController <TownListViewControllerDelegate> {
...
}
SearchViewController.m
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
TownListViewController * townViewController = [[TownListViewController alloc] initWithNibName:@"TownListViewController" bundle:nil];
townViewController.delegate = self;
[self.navigationController pushViewController:townViewController animated:YES];
}
- (void)didSelectTown:(Town *)town
{
NSLog(@"didSelectTown fired");
self.selectedTown = town;
}
任何幫助,非常感謝。
你委託執行是正確的。我總是會檢查委託是否響應選擇器,因爲你聲明委託方法是可選的,所以如果你的對象沒有實現,你會得到一個崩潰。你的問題可能在didSelectRowAtIndexpath中 - 它肯定會被調用嗎? – Rog
現貨!我認爲這個方法是將TownListViewController推向堆棧(didSelectRowAtIndexPath)時未被調用,而是被另一個未設置委託的方法所推送。另一個說明,我試圖添加respondsToSelector,但它出現說「-respondsToSelector not found」,有什麼想法? –
'if([self.delegate respondsToSelector:@selector(didSelectTown :)]){[self.delegate didSelectTown:town];}' – Rog