2014-01-08 33 views
2

我在這裏丟失了什麼?我只是試圖從一個模式視圖控制器發送一個簡單的通知回到啓動它的視圖控制器,但沒有收到任何東西。從Modal ViewController未收到NSN通知

這是在視圖控制器啓動模態SEGUE的代碼:

- (IBAction) chooseSuperGroup:(UIButton *)sender { 
    NSLog(@"super group choice about to be made"); 

    [[NSNotificationCenter defaultCenter] addObserver:self 
              selector:@selector(choiceReceived:) 
               name:@"selectionMade" 
               object:self]; 
} 

- (void) choiceReceived: (NSNotification *) notification 
{ 
    NSLog(@"here"); 
    if ([[notification name] isEqualToString:@"selectionMade"]) { 
     NSLog(@"received"); 
     NSLog(@"%@", (NSString *)[notification userInfo]); 
    } 

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

然後,在中模態視圖控制器,當用戶選擇從表視圖細胞代碼執行:

NSDictionary *dict = [NSDictionary dictionaryWithObject:selection forKey:@"superGroup"]; 

NSLog(@"printing dictionary contents"); 
for (id key in dict) { 
    NSLog(@"key: %@ object: %@", key, [dict objectForKey:key]); 
} 

[[NSNotificationCenter defaultCenter] postNotificationName:@"selectionMade" object:self userInfo:dict]; 

我的輸出是這樣的:

Super group choice about to be made 
printing dictionary contents 
key: superGroup object: myChoice 

所以在選擇時被捕獲並添加到字典中。但沒有收到任何通知的證據。這不是那麼難,但我沒有看到我的錯誤。有人能幫我嗎?謝謝!

回答

4

嘗試使用 '零',而不是 '自我'

//添加觀察

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(choiceReceived:) name:@"selectionMade" object:nil]; 

//刪除觀察

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

//張貼通知

[[NSNotificationCenter defaultCenter] postNotificationName:@"selectionMade" object:nil userInfo:dict]; 

參考:https://stackoverflow.com/a/8188759/2449268

+0

這是它。我在觀察者一方嘗試過'nil',但不是在通知方一側。謝謝! – Alex

+0

另外,當你用'object:nil'(意思是:我會接受來自任何對象的通知)註冊通知的時候,通常用* object * self來通知* post *,它只是通過對象對於聽衆來說,如果他們在意詢問發件人。在收到通知方面,註冊結束時「無」。 – Olie