iphone - 从observeValueForKeyPath 调用方法。

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

这是我第一次使用 KVO,我立刻就陷入了困境。问题是,当调用observeValueForKeyPath 时,我正在调用同一个类中的另一个方法。该方法只是显示一个警报 View 。我认为很简单,但警报 View 没有显示。

- (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是在主线程上创建的。

关于iphone - 从observeValueForKeyPath 调用方法。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11618876/

相关文章:

ios - View 内部的 TableView , View Controller 内部。最好的方法是什么?

ios - 适用于 iOS 的统一构建 : Not able to change Bundle Identifier

iphone - 在 UIImage 顶部绘制透明圆圈 - iPhone SDK

iphone - 如何将日期字符串从 twitter 设置为 NSDATE

objective-c - NSInvalidArgumentException',原因 : '-[__NSCFString isFileURL]: unrecognized selector sent to instance 0x712e450'

ios - 转至 Storyboard Reference 后出错

ios - iPhone可以通过麦克风检测数字信号吗?

ios - 使用手势识别器

ios - 将 UIButton 添加到 UITableViewCell 以防搜索无结果,空数组

ios - 当 UICollectionView 位于 iOS 中的自定义 TableViewCell 内时,如何实现 UICollectionView 的委托(delegate)和数据源方法, Objective-C