2014-01-15 57 views
0

我有一个视图我想显示某个事件。我的视图控制器正在侦听由模型发送的广播通知,并且它在接收广播时尝试显示视图。如果显示响应通知,则不会显示查看,但不会显示

但是该视图没有出现。但是如果我在视图控制器的其他地方运行完全相同的视图代码,那么它将被显示。这里有一些来自VC的代码来说明:

- (void) displayRequestDialog 
{ 
    MyView *view = (MyView*)[[[NSBundle mainBundle] loadNibNamed:@"MyView" owner:self options:nil] objectAtIndex:0]; 
    view.backgroundColor = [UIColor lightGrayColor]; 
    view.center = self.view.window.center; 
    view.alpha = 1.0; 
    [self.view addSubview:view]; 
} 

- (void) requestReceived: (NSNotification*) notification 
{ 
    [self displayRequestDialog]; 
} 

当上面的代码运行时,视图不会出现。但是,如果我在其他地方添加了对displayRequestDialog的调用,例如viewDidAppear:

- (void) viewDidAppear 
{ 
    [self displayRequestDialog]; 
} 

然后显示它。

因此,我的问题显然是为什么我可以从viewDidLoad调用displayRequestDialog成功出现视图,但如果从requestReceived中调用它,则不会显示?

(请注意,我不是视图控制器之前过早地调用requestReceived /视图加载和显示)

起初我张贴这样的通知:

[[NSNotificationCenter defaultCenter] postNotificationName: kMyRequestReceived 
                  object: self 
                  userInfo: dictionary]; 

然后我想这:

NSNotification *notification = [NSNotification notificationWithName:kMyRequestReceived object:self userInfo:dictionary]; 
    NSNotificationQueue *queue = [NSNotificationQueue defaultQueue]; 
    [queue enqueueNotification:notification postingStyle:NSPostWhenIdle]; 

然后我尝试这样的:

dispatch_async(dispatch_get_main_queue(),^{ 
    [[NSNotificationCenter defaultCenter] postNotificationName: kMyRequestReceived 
                 object: self 
                 userInfo: dictionary]; 
}); 

然后我尝试这样做:

[self performSelectorOnMainThread:@selector(postNotificationOnMainThread:) withObject:dictionary waitUntilDone:NO]; 

- (void) postNotificationOnMainThread: (NSDictionary*) dict 
{ 
    [[NSNotificationCenter defaultCenter] postNotificationName: kMyRequestReceived 
                 object: self 
                userInfo: dict]; 
} 

我试图调用displayRequestDialog这样的:

dispatch_async(dispatch_get_main_queue(),^{ 
     [self displayRequestDialog]; 
}); 

我已经找到了视图不显示的原因 - 该帧的原点当通过通知代码调用时获得负值,而当调用时则为正值,从而在屏幕上显示。 不知道为什么应该有所不同。

+0

你在发送通知的线程是什么?请注意,通知可能在bg线程上发送,并且您的UI也在bg线程中调用。 – danypata

+0

尝试调度到requestReceived中的主线程? – Jack

+0

显示如何注册通知。 – Peres

回答

0

您没有收听通知。这样做是这样的:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(displayRequestDialog) name:kMyRequestReceived object:nil]; 
+0

这不是问题,接收到通知并且正在调用displayRequestDialog方法。 – Gruntcakes

0

据我们不能看到代码用于注册您的控制器接收通知我建议你使用哪一个执行主线程“上免费获取通知的观察者登记方法“

[[NSNotificationCenter defaultCenter] addObserverForName:@"Notification" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) { 
    NSLog(@"Handle notification on the main thread"); 
}]; 
+0

谢谢,我找到了原因,看到我自己的答案。至于为什么会发生这种情况,我会很好奇的发现。 – Gruntcakes