2013-04-01 22 views
1

我聲明瞭一個協議方法以便由其委託調用。這是相關的代碼:調用導航堆棧中的協議方法

其中協議delared視圖:

CategoryViewController.h

@class CategoryViewController; 
@protocol CategoryViewControllerDelegate<NSObject> 
-(void)loadProductsList:(id)sender; 


@end 

@interface CategoryViewController : UIViewController<UITableViewDataSource,UITableViewDelegate> 
{ 

    id delegate; 

} 

@property(nonatomic, strong)id <CategoryViewControllerDelegate>delegate; 

CategoryViewController.m

@implementation CategoryViewController 

@synthesize delegate; 

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
    { 
      CategoryViewController *catView = [[CategoryViewController alloc] initWithNibName:@"CategoryViewController" bundle:nil]; 
      [self.navigationController pushViewController:catView animated:YES]; 

      if([self.delegate respondsToSelector:@selector(loadProductsList:)]){ 
       [self.delegate loadProductsList:[arrayCategory objectAtIndex:indexPath.row]]; 
      } 
    } 

委託觀點被稱爲MainViewController,在MainViewController viewDidLoad方法,我委託設置爲self:

-(void)viewDidLoad{ 
    //Use a property of CategoryViewController to set the delegate 

    self.categoryController.delegate = self; 
} 

-(void)loadProductsList:(id)sender{ 
//Logic 


} 

讓我向你解釋一下,CategoryViewControllerUINavigationController所以當點擊一個細胞,我創建管理一個CategoryViewController的新實例並將其推送到導航堆棧。然後我打電話到協議方法:

if([self.delegate respondsToSelector:@selector(loadProductsList:)]){ 
    [self.delegate loadProductsList:[arrayCategory objectAtIndex:indexPath.row]]; 
    } 

的問題是,該委託僅對根視圖,當CategoryViewController本視圖是0的索引。然後委託爲空,因此協議方法loadProductsList:無法在我嘗試從堆棧視圖索引1,2等調用協議方法時觸發。當我回到索引0(導航堆棧中的根視圖)時,委託對象有效再次,我可以調用協議方法。

我的問題是:

爲什麼在我創建的CategoryViewController一個新的實例我不能開除協議的方法,並將它推到導航堆棧?爲什麼委託對象會變爲null呢?提前Thanx。

回答

2

您只爲一個(第一個)CategoryViewController類設置委託。

每次選擇某一行時,您都會創建一個新的CategoryViewController類,該類的委託爲零,因爲您尚未設置它。

編輯,

我在這裏看到兩個選項。

a)你可以爲MainController做一個單例,所以你可以從你的代碼中的任何一點訪問它。然後,您可以將其設置爲didSelectRowAtIndexPath作爲委託。

B)喲可以recusively通過委託

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
     CategoryViewController *catView = [[CategoryViewController alloc] initWithNibName:@"CategoryViewController" bundle:nil]; 
     [self.navigationController pushViewController:catView animated:YES]; 

     catView.delegate = self.delegate; 

     if([self.delegate respondsToSelector:@selector(loadProductsList:)]){ 
      [self.delegate loadProductsList:[arrayCategory objectAtIndex:indexPath.row]]; 
     } 
} 
+0

嗨,我確信這一點,但如何創建一個新的'CategoryViewController'後設置委託。設置委託在'MainViewController'' viewDidLoad'方法中完成,並且在'CategoryViewController'類中完成創建新的'CategoryViewController'。那讓我困惑的是,我可以從'CategoryViewController'類中設置委託嗎?我不這麼認爲。 – Malloc

+0

編輯答案 – pdrcabrod

+0

+1我採用了b解決方案,而且效果很好。 Thanx男人:) – Malloc