iphone - NSNotificationCenter 的大问题,它不会更新目标的显示

标签 iphone objective-c uiview instance nsnotificationcenter

救命,我很绝望..因此我无法继续我的应用程序:

我在 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/

相关文章:

objective-c - Dropbox 的所有文件夹及其内部文件夹的列表

objective-c - 使用 objective-c 自定义 UIView

ios - 响应 child 和 parent 的触摸事件

ios - 自定义 MKAnnotation 标注气泡

iphone - 我们可以定义一个私有(private)的 IBOutlet 吗?

iphone - 如何使用 MPMoviePlayerController 或 AVPlayer 在 iOS 上播放没有文件扩展名的电影文件?

ios - 如何基于平移手势放大/缩小 UIView?

ios - 按时间错误使用 NSSortDescriptor 排序(带有核心数据)

iphone - 如何卸载 UIViewController 的 View

ios - UIView Controller 中的通知未触发