2010-11-05 36 views
3

我想要在專用於音頻的線程中運行的事件來更改UI。簡單地調用view.backgroundColor似乎沒有任何效果。iOS:從運行循環外部設置UIView背景顏色

這裏是我的viewController中的兩個方法。第一個是觸摸觸發的。第二個是從音頻代碼中調用的。第一部作品。第二。任何想法爲什麼?

// this changes the color 
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{ 
    [touchInterpreter touchesMoved:touches withEvent:event]; 
    self.view.backgroundColor = [UIColor colorWithWhite: 0.17 + 2 * [patch getTouchInfo]->touchSpeed alpha:1]; 

}; 

// this is called from the audio thread and has no effect 
-(void)bang: (float)intensity{ 
    self.view.backgroundColor = [UIColor colorWithWhite: intensity alpha:1]; 
} 

任何想法爲什麼?我只是在做一些愚蠢的事情,還是有一種竅門可以從運行循環之外改變UI元素?

回答

6

從主線程以外的任何地方觸摸UI都是不允許的,並且會導致奇怪的行爲或崩潰。在iOS 4.0或更高版本,你應該使用類似

- (void)bang:(float)intensity { 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     self.view.backgroundColor = [UIColor colorWithWhite:intensity alpha:1]; 
    }); 
} 

還是NSOperationQueue變種

- (void)bang:(float)intensity { 
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{ 
     self.view.backgroundColor = [UIColor colorWithWhite:intensity alpha:1]; 
    }]; 
} 

在iOS 3.2或更早版本,您可以使用[self performSelectorOnMainThread:@selector(setViewBackgroundColor:) withObject:[UIColor colorWithWhite:intensity alpha:1] waitUntilDone:NO],然後就定義

- (void)setViewBackgroundColor:(UIColor *)color { 
    self.view.backgroundColor = color; 
} 

注調用[self.view performSelectorOnMainThread:@selector(setBackgroundColor:) withObject:[UIColor colorWithWhite:intensity alpha:1] waitUntilDone:NO]是不安全的,因爲UIViewController的view屬性不是線程安全的。

+0

非常感謝! – morgancodes 2010-11-05 12:48:36