2015-07-05 47 views
-2

我想在另一個控制器中創建一個UITableViewController,並且從該控制器傳遞一個方法。我已經讀過這可以通過使用@selector來實現。現在,我嘗試了以下內容:在另一個類中執行一個選擇器

TimeController.m

- (void)choseTime{ 
    SelectOptionController *selectController = [[SelectOptionController alloc] initWithArray:[Time SQPFetchAll] andSelector:@selector(timeSelected)]; 
    [self.navigationController pushViewController:selectController animated:true]; 
} 

- (void) timeSelected{ 
    NSLog(@"Time selected!"); 
} 

SelectOptionController.h

@interface SelectOptionController : UITableViewController 

@property (nonatomic, strong) NSMutableArray *dataset; 
@property (nonatomic) SEL selectedMethod; 

-(id)initWithArray: (NSMutableArray *) myArray andSelector: (SEL) selectedMethod; 

SelectOptionController.m

- (id)initWithArray: (NSMutableArray *) myArray andSelector: (SEL) selectedMethod{ 
    self = [super initWithStyle:UITableViewStyleGrouped]; 
    if(self) { 
     self.dataset = myArray; 
     self.selectedMethod = selectedMethod; 
    } 
    return self; 
} 

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ 
    [self performSelector:self.selectedMethod]; 
    [self.navigationController popViewControllerAnimated:true]; 
} 

然而,當細胞被選中,以下異常被拋出:

-[SelectOptionController timeSelected]: unrecognized selector sent to instance 0x1450f140 

我在這裏做錯了什麼?任何幫助將不勝感激。

+1

尋求調試幫助的問題(「爲什麼這個代碼不工作?」)必須包含所需的行爲,特定的問題或錯誤以及在問題本身中重現問題所需的最短代碼。 –

回答

3

您在self上調用timeSelected,它實際上是SelectOptionController,但timeController類中存在timeSelected方法。

假設您不想將timeSelected移動到SelectOptionController,您需要將對TimeController的引用傳遞給新的SelectOptionController並對其調用選擇器。選擇器只是對方法的引用,而不是方法本身。你可能也想把它作爲一個弱引用存儲。

E.g.

@interface SelectOptionController : UITableViewController 

@property (nonatomic, strong) NSMutableArray *dataset; 
@property (nonatomic) SEL selectedMethod; 
@property (nonatomic, weak) TimeController *timeController; 

而且

- (id)initWithArray: (NSMutableArray *) myArray andSelector: (SEL) selectedMethod timeController:(TimeController*)timeController { 
    self = [super initWithStyle:UITableViewStyleGrouped]; 
    if(self) { 
     self.dataset = myArray; 
     self.selectedMethod = selectedMethod; 
     self.timeController = timeController; 
    } 
    return self; 
} 

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ 
    [self.timeController performSelector:self.selectedMethod]; 
    [self.navigationController popViewControllerAnimated:true]; 
} 

與所述所有這一切,上面會得到你的代碼的工作,但是這是不是一個特別好的模式。我建議你看看Prototypes and Delegates來實現這個行爲,或者如果你想通過這個方法本身,請在Blocks上做一些研究。但希望這可以幫助你更好地理解選擇器如何工作。

+0

感謝您的幫助,它現在正在工作。我想要做的是推送TableViewController並將其用作Pickerview,以便用戶可以選擇一行。當選中一行時,我希望將這些數據傳遞給父視圖,以便我可以在那裏使用它。有沒有更好的方式來做到這一點,然後通過選擇器? – Tomzie

+0

我會爲您的SelectOptionController和弱代理屬性實現一個協議。一個協議基本上定義了你的委託所期望的方法(和/或屬性)。在初始化SelectOptionController時,將代理設置爲'self'(即TimeController),並確保TimeController符合您新創建的協議。然後你可以調用你在委託中定義的方法(來自SelectOptionController)。如果你之前沒有使用協議,我會建議對它們的工作方式進行一些研究。 – JoGoFo

相關問題