2

帮助,我很沮丧..我无法继续我的应用程序,因为:

我已经在我的 2 个 cocoa objective-c 类之间设置了一条消息,主要的 appdelegate 正在通过 NSNotificationCenter 向视图发送消息,该视图确实收到了通知,但不知何故它无法更新视图上可见的控件.. 就像它可以'找不到合适的实例或其他东西。

这是我的代码:mainapp(appdelegate 向我发送消息):

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 并将其分配给此视图的按钮并执行相同操作: [self.mybutton setTitle:@"sdsdsdasd" forState:UIControlStateNormal]; 它将毫无问题地更新我的显示...修改标题...

那么NSnotificationcenter调用的函数和属于同一个视图的函数有什么区别...

我试图在这两种情况下查看 self 变量的地址,结果是相同的......所以..基本上使用相同的指针对吗?

还是不行……

几天前我又发了一篇文章..但没有人回答 以 编程方式创建的标签和图像未显示在屏幕上

4

2 回答 2

3

听起来很像您的NewMessageNotification:方法没有在主线程上被调用;UI 更新只能从主线程完成,否则将无法正常工作。

对于这种情况,通常的习惯用法是这样的:

- (void)NewMessageNotification:(NSNotification *)notification
{
    if (![NSThread isMainThread]) {
        [self performSelectorOnMainThread:@selector(NewMessageNotification:) withObject:notification waitUntilDone:NO];
        return;
    }

    // Existing code goes here
}
于 2011-03-26T18:59:07.120 回答
0

听起来您可能有两个不同的类实例,其中一个连接到 nib 中的所有内容,其中一个正在注册通知。尝试登录self该方法,当通知与按钮触发它时,您可能会看到不同的对象地址。

于 2011-03-25T22:18:54.833 回答