2012-12-06 112 views
0

我有一個while語句在後臺運行。iOS:performSelectorOnBackground/MainThread:不更新標籤

- (IBAction)startButton 
{ 
[self performSelectorInBackground:@selector(Counter) withObject:nil]; 
..... 
} 

- (void) Counter 
{ 
    while (round) { 
    if (condition) 
    { 
    NSString *str; 
    str = [NSString stringWithFormat:@"%d",counter]; 
    [self performSelectorOnMainThread:@selector(updateLabel:) withObject:str waitUntilDone:NO];  
    } 
    } 
} 
- (void)updateLabel: (NSString*) str 
{ 
[self.label setText:str]; 
NSLog(@"I am being updated %@",str); 
} 

NSlog獲取正確的更新值,但標籤永遠不會更新。

我在做什麼錯?

更新:

標籤連接,並完成了while語句之後,它就會被更新過的。

另外我已初始化標籤。

- (void)viewDidLoad 
{ [super viewDidLoad]; 
label.text = @"0"; 
} 
+0

我懷疑self.label是零,因爲你的實際標籤是在另一個實例中,或者它根本就沒有連接。 –

+0

你可以展示你如何運行while循環「在後臺」?我懷疑你是在主線程上運行它。 – omz

+0

檢查我的更新:我使用[self performSelectorInBackground:@selector(Counter)withObject:nil]; – alandalusi

回答

2

檢查IBOutlet中是否連接在界面生成器

EDIT 3

嘗試調度使用GCDdispatch_async請求,所以它成爲

while (round) { 
    if (condition) 
    { 
    NSString * str = [NSString stringWithFormat:@"%d",counter]; 
    dispatch_async(dispatch_get_main_queue(),^ { 
     [self updateLabel:str]; 
    }); 
    } 
} 

另一種方式來更新UILabel是設置NSTimer每秒(根據您的需要)更新它,而不是與while循環。

這將是像

NSTimer * updateLabelTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(updateLabel) userInfo:nil repeats:YES]; 

-(void)updateLabel { 
    if(condition) { 
    self.label.text = [NSString stringWithFormat:@"%d", counter]; 
    } 
} 
+0

是的,它聽起來很愚蠢,但我有完全相同的問題和完全相同的解決方案。 – Minthos

+0

這就是您決定如何從代碼構建UI而不是使用Interface Crappy Builder的原因。 – 2012-12-06 17:56:09

+0

哈哈不,IB有其侷限性,但它可以節省大量的工作。 – Minthos

0

嘗試

dispatch_after(DISPATCH_TIME_NOW, dispatch_get_main_queue(), ^(void){ 
    [self updateLabel:str]; 
}); 

我只是喜歡這種過度performSelectorOnMainThread:withObject:waitUntilDone:

如果不行,請檢查label是否爲零。如果是,那麼通過更多的代碼。

編輯時,最前一頁評論:

NSTimer能幫上忙,但本應正常工作。

- (IBAction)startButton 
{ 
    [self Counter]; 
} 

- (void) Counter 
{ 
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 

     while (round) { 
      if (condition) 
      { 
       NSString *str; 
       str = [NSString stringWithFormat:@"%d",counter]; 

       dispatch_async(dispatch_get_main_queue(), ^{ 
        [self updateLabel:str]; 
       }); 
      } 
     } 

    }); 

} 
- (void)updateLabel: (NSString*) str 
{ 
    [self.label setText:str]; 
    NSLog(@"I am being updated %@",str); 
} 
+0

lable不是零,即使使用調度後問題依然存在 – alandalusi

+0

我更新了我的答案。 – user500

1

你的主線程可能等待你的後臺線程來完成。你是如何在後臺線程上啓動任務的?

+0

我用[self performSelectorInBackground:@selector(Counter)withObject:nil]; – alandalusi