2

問題,我希望我有一個人幫助我在這一個更好的運氣:與NSNotificationCenter和UIPickerView

我是用戶進行選擇一個UIPickerView,然後按下按鈕。我可以很高興地獲得用戶的選擇,如我的NSLog所示,並且完成後,我想向另一個視圖控制器發送通知,該視圖控制器將顯示帶有所選選項的標籤。那麼,儘管看起來一切都是正確的,但它不起作用並且標籤保持不變。下面是代碼:

播音員:

if ([song isEqualToString:@"Something"] && [style isEqualToString:@"Other thing"]) 

{ 
    NSLog (@"%@, %@", one, two); 
    [[NSNotificationCenter defaultCenter] postNotificationName:@"Test1" object:nil]; 

ReceiverViewController *receiver = [self.storyboard instantiateViewControllerWithIdentifier:@"Receiver"]; 
    [self presentModalViewController:receiver animated:YES]; 

} 

觀察報:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{ 
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
    if (self) 
{ 
    [[NSNotificationCenter defaultCenter] addObserver:self  selector:@selector(receiveNotification) name:@"Test1" object:nil]; 
} 
    return self; 
} 

-(void)receiveNotification:(NSNotification*)notification 
{ 

if ([[notification name] isEqualToString:@"Test1"]) 
{ 

    [label setText:@"Success!"]; 
    NSLog (@"Successfully received the test notification!"); 
} 

else 

{ 
    label.text = @"Whatever..."; 
} 


} 

回答

0

的問題很可能是發送通知(並因此得到),在不同的線程比主線程。只有在主線程中,您才能更新UI元素(如標籤)。

查看我對this question的回答,以獲取有關線索和NSNotifications的一些見解。

使用類似:方法正在執行:

NSLog(@"Code executing in Thread %@",[NSThread currentThread]); 

到你的主線程與您recieveNotifcation哪裏比較。

如果您不在發送通知的線程不是主線程的情況下,解決方案可能是播放你nsnotifications出主線程像這樣:

//Call this to post a notification and are on a background thread  
- (void) postmyNotification{ 
    [self performSelectorOnMainThread:@selector(helperMethod:) withObject:Nil waitUntilDone:NO]; 
} 

//Do not call this directly if you are running on a background thread. 
- (void) helperMethod{ 
    [[NSNotificationCenter defaultCenter] postNotificationName:@"SOMENAME" object:self]; 
} 

如果你只關心主線程上正在更新的標籤,你可以使用類似的東西在主線程上執行該操作:

dispatch_sync(dispatch_get_main_queue(), ^(void){ 
          [label setText:@"Success!"]; 
         }); 

希望對你有幫助!

1

我認爲你的選擇器有一個語法錯誤:@selector(receiveNotification)。由於您的方法接受NSNotification *notification消息,因此它應該帶有冒號@selector(receiveNotification:)。沒有它,這是一個不同的簽名。