2

我希望有人帮我解决这个问题,我有更好的运气:

我有一个 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...";
}


}
4

2 回答 2

1

我认为您的选择器中有语法错误:@selector(receiveNotification). 它可能应该@selector(receiveNotification:)带有冒号,因为您的方法接受该NSNotification *notification消息。没有它,这是一个不同的签名。

于 2014-01-29T04:30:44.573 回答
0

该问题很可能是在与主线程不同的线程上发送(并因此接收)通知。只有在主线程上,您才能更新 UI 元素(如标签)。

有关线程和 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!"];
                        });

希望这有帮助!

于 2011-12-11T16:14:13.063 回答