救命,我很绝望..因此我无法继续我的应用程序:
我在 2 个 cocoa Objective-C 类之间设置了一条消息, 主要的 appdelegate 通过 NSNotificationCenter 发送 View 消息 View 确实收到了通知,但不知何故它无法更新 View 上可见的控件..就像它找不到正确的实例或其他东西一样。
这是我的代码: mainapp(appdelegate 向我的 View 发送消息的地方):
helloKey = @"0";
helloString = @"mymessage";
values = [NSMutableDictionary dictionaryWithObject:helloString forKey:helloKey];
[[NSNotificationCenter defaultCenter] postNotificationName:@"NewMessageNotification" object:self userInfo:values];
该函数在 myuiviewcontoler 中定义
- (void)NewMessageNotification:(NSNotification *)notification
{
// key associated with string "Hello String"
helloKey = @"0";
// [notificaiton userInfo] returns "values"
helloFromMain = [[notification userInfo] objectForKey:helloKey];
NSLog(@"newmess=%@",helloFromMain; //this outputs mymessage , perfect right?? not quite..here's the problem
//then if I'm trying to update something visible ..it won't do IT!!!! :( :(
//tested with the debugger and it reaches this line...when the messaging occurs
[self.mybutton setTitle:@"sdsdsdasd" forState:UIControlStateNormal];
//this won't work, not it will give an error!!!
}
那么这可能是什么问题呢?使用此功能时,无法以编程方式修改任何可见的内容,我非常需要它..
如果我执行 IBAction 并将其分配给此 View 的按钮并执行相同的操作: [self.mybutton setTitle:@"sdsdsdasd"forState:UIControlStateNormal]; 它会毫无问题地更新我的显示...修改标题...
那么NSnotificationcenter调用的函数和属于同一个 View 的函数有什么区别...
我试图查看两种情况下 self 变量的地址,结果是相同的...... 所以..基本上使用相同的指针,对吧?
还是不行...
几天前我又发了一篇帖子..但没有人回复 Programatically created labels and images don't show on screen
最佳答案
听起来很像您的 NewMessageNotification:
方法没有在主线程上调用; UI 更新只能从主线程完成,否则将无法正常工作。
类似这种情况的惯用语是这样的:
- (void)NewMessageNotification:(NSNotification *)notification
{
if (![NSThread isMainThread]) {
[self performSelectorOnMainThread:@selector(NewMessageNotification:) withObject:notification waitUntilDone:NO];
return;
}
// Existing code goes here
}
关于iphone - NSNotificationCenter 的大问题,它不会更新目标的显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5438662/