2014-01-14 42 views
0

我有一個模型UIViewController其上有一個UITableView。對於用戶選擇的任何單元格,我想將該文本返回到先前的視圖控制器並關閉模態視圖。我正在使用NSNotifications將值發回。問題是,我的通知從未收到。NS通知沒有返回

這裏是從「父」視圖代碼:

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    [[NSNotificationCenter defaultCenter] addObserver:self 
              selector:@selector(choiceReceived:) 
               name:@"selectionMade" 
               object:nil]; 

    [self performSegueWithIdentifier: @"locationsDetailsSegue" sender: self]; 
} 

- (void) choiceReceived: (NSNotification *) notification 
{ 
    NSLog(@"test"); 

    NSDictionary *dict = [notification userInfo]; 
    NSString *user_choice = [dict objectForKey:@"choice"]; 

    NSLog(@"%@", user_choice); 

    [[NSNotificationCenter defaultCenter] removeObserver:self 
                name: @"selectionMade" 
                object:nil]; 
} 

而在模態視圖控制器:

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath]; 
    NSString *choice = cell.textLabel.text; 

    // send a notification of this choice back to the 'parent' controller 
    NSDictionary *dict = [NSDictionary dictionaryWithObject:choice forKey:@"choice"]; 
    [[NSNotificationCenter defaultCenter] postNotificationName:@"selectionMade" object:nil userInfo:dict]; 

    NSLog(@"%@", [dict objectForKey:@"choice"]); 

    [self dismissViewControllerAnimated:YES completion:nil]; 
} 

我從通知輸出正確的,但我沒有得到任何輸出無論從接收器。我錯過了明顯的東西嗎?謝謝!

+1

當通知發佈時,原始VC肯定還活着嗎? –

+1

在tableView:didSelectRowAtIndexPath:的模式視圖控制器實現之前,總是調用'tableView:didSelectRowAtIndexPath:'的父視圖實現嗎?這些是不同的tableViews,對吧? – ThomasW

+0

@JoshCaswell - 我不是100%確定。原始的VC以模態方式調用這個VC,所以我相信它仍然存在,但我不知道如何驗證。我在其他情況下使用這種模式,並且一直有效,所以我不知道它爲什麼會失敗。我想我會研究委託模式,因爲無論如何我需要了解這一點。 – Alex

回答

4

嗯,我不喜歡在這種情況下使用NSNotificationCenter它只是我的建議)。在這種情況下,我總是推薦委託模式。委派模式可以處理或傳遞一對一對象通知,因此它可以提供100%精確的輸出並消除其他衝突。
在childviewcontroller中創建協議方法,並在parentclassviewcontroller中通過委託屬性進行確認。 在parentviewcontroller中使用chileviewcontroller協議。在parentviewcontroller類中實現所需的委託代理方法。你也可以通過委託方法發送多種類型的參數。 欲瞭解更多信息,請通過此doc

+0

謝謝。我花了一些時間,並加快了委託模式。更可靠。 – Alex