2011-09-08 69 views
0

我想構建一個委託讓我將數據從一個子視圖控制器傳遞給父級。我一直在網上查看各種教程/問題,但我的委託方法沒有被觸發。爲什麼不是我的自定義代理工作?

你可以看看我的代碼在下面,看看我是否失去了什麼?

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; 
} 

任何幫助,非常感謝。

+2

你委託執行是正確的。我總是會檢查委託是否響應選擇器,因爲你聲明委託方法是可選的,所以如果你的對象沒有實現,你會得到一個崩潰。你的問題可能在didSelectRowAtIndexpath中 - 它肯定會被調用嗎? – Rog

+0

現貨!我認爲這個方法是將TownListViewController推向堆棧(didSelectRowAtIndexPath)時未被調用,而是被另一個未設置委託的方法所推送。另一個說明,我試圖添加respondsToSelector,但它出現說「-respondsToSelector not found」,有什麼想法? –

+0

'if([self.delegate respondsToSelector:@selector(didSelectTown :)]){[self.delegate didSelectTown:town];}' – Rog

回答

0

嘗試在設置委託後重新載入數據。我覺得到餐桌的reloadData第一呼叫TownListViewController的initWithNibName ......期間,您可以張貼在此方法delegate值發生總之:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 

我打賭是零......

由方法是一個很好的做法,檢查變量delegate符合該協議,嘗試在假設的方法是可選加入這一行:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    if([delegate conformsToProtocol(TownListViewControllerDelegate)] && [delegate respondsToSelector:@selector(didSelectTown:objectAtIndexPath:)]) 
     [delegate didSelectTown:(Town *)[self.fetchedResultsController objectAtIndexPath:indexPath]]; 
    [self.navigationController popViewControllerAnimated:YES]; 
} 
+0

感謝您的評論。最後的解決方案是設置代理的didSelectRowAtIndexPath在我期待時沒有被調用。至於你的良好做法提示,我試圖添加respondsToSelector,但它出現說「-respondsToSelector not found」,有什麼想法? –

相關問題