从observeValueForKeyPath调用方法。

时间:2012-07-23 19:07:57

标签: iphone objective-c ios key-value-observing

这是我第一次使用KVO而且我立即被卡住了。问题是当observeValueForKeyPath被调用时,我正在调用同一个类中的另一个方法。而这种方法只是显示一个警报视图。我想的简单的事情,但警报视图不显示。

- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object 
                     change:(NSDictionary *)change context:(void *)context
{
    [self beginUpdate];
}


 -(void)beginUpdate
 {
     NSLog(@"Check!");
     UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"message" message:@"Hi" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
     [alert show];
 } 

显示日志消息。警报消息仅显示我是否通过observeValueForKeyPath之外的任何其他方法调用它。

1 个答案:

答案 0 :(得分:5)

据我所知,observeValueForKeyPath:在修改被观察对象的线程的上下文中被调用。另一方面,UI的更改只能在主线程上完成。尝试

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

[self performSelectorOnMainThread:@selector(beginUpdate) withObject:nil waitUntilDone:NO]

确保在主线程上创建UIAlertView