来自observeValueForKeyPath的调用方法。
问题描述:
这是我第一次使用KVO,并且马上就卡住了。问题是,当observeValueForKeyPath被调用时,我正在调用同一个类中的另一个方法。并且该方法仅显示一个警报视图。我认为简单的事情,但警报视图不显示。来自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之外的其他方法调用它时,才会显示警报消息。
答
据我所知,observeValueForKeyPath:
是在修改观察对象的线程的上下文中调用的。另一方面,只能在主线程上对UI进行更改。尝试
dispatch_async(dispatch_get_main_queue(), ^{
[self beginUpdate];
});
或
[self performSelectorOnMainThread:@selector(beginUpdate) withObject:nil waitUntilDone:NO]
,以确保UIAlertView
是主线程上创建。