2012-07-23 69 views
2

這是我第一次使用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之外的其他方法調用它時,纔會顯示警報消息。

回答

5

據我所知,observeValueForKeyPath:是在修改觀察對象的線程的上下文中調用的。另一方面,只能在主線程上對UI進行更改。嘗試

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

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

,以確保UIAlertView是主線程上創建。