2013-10-08 26 views
0

我在我的應用程序中使用了MBProgressHUD庫,但有時甚至進度hud甚至沒有顯示當我查詢大量數據或在數據處理已完成(到那時我不再需要顯示hud)。在iOS中使用NSThread和自動釋放池的有效方法

在另一篇文章中,我發現有時UI運行週期非常繁忙以至於無法完全刷新,所以我使用了部分解決了問題的解決方案:現在,每個請求都會提升HUD,但幾乎有一半次應用程序崩潰。爲什麼?這是我需要幫助的地方。

我有一個表視圖,在委託方法didSelectRowAtIndexPath方法我有這樣的代碼:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{  
    [NSThread detachNewThreadSelector:@selector(showHUD) toTarget:self withObject:nil]; 
    ... 
} 

然後,我有這樣的方法:

- (void)showHUD { 
    @autoreleasepool { 
     [HUD show:YES]; 
    } 
} 

在其他一些時候,我只要致電:

[HUD hide:YES]; 

還有,它工作時它工作,hud顯示,保持然後消失,如預期d,有時它只是使應用程序崩潰。錯誤:EXC_BAD_ACCESS。爲什麼?

順便說一句,在HUD對象已經被分配在viewDidLoad中:

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    ... 

    // Allocating HUD 
    HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view]; 
    [self.navigationController.view addSubview:HUD]; 

    HUD.labelText = @"Checking"; 
    HUD.detailsLabelText = @"Products"; 
    HUD.dimBackground = YES; 
} 
+0

你也在做主線程處理嗎? – chedabob

+0

是的,我正在快速枚舉一些數組,填充一些對象,在集合視圖中顯示事物......是的,我認爲所有這些都是在主線程上完成的...... – Renexandro

回答

0

您需要在另一個線程執行的處理,否則處理阻止MBProgressHud拉,直到它完成,此時MBProgressHud被再次隱藏。

NSThread對於卸載處理來說有點太低級別。我建議Grand Central Dispatch或NSOperationQueue。

http://jeffreysambells.com/2013/03/01/asynchronous-operations-in-ios-with-grand-central-dispatch http://www.raywenderlich.com/19788/how-to-use-nsoperations-and-nsoperationqueues

/* Prepare the UI before the processing starts (i.e. show MBProgressHud) */ 

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
    /* Processing here */ 

    dispatch_async(dispatch_get_main_queue(), ^{ 
     /* Update the UI here (i.e. hide MBProgressHud, etc..) */  
    }); 
}); 

這個片段將讓你做的主線程上的任何UI工作,分派處理到另一個線程之前。然後,一旦處理完成,它就會返回到主線程,以允許您更新UI。

+0

但是處理是在委託方法,didSelectRowAtIndexPath在這種情況下,我怎麼能在另一個線程上做這個處理? MBProgress Show和Process都在didSelect中......我怎樣才能將它們分開在不同的線程中? – Renexandro

+0

將代碼片段粘貼到didSelectRowAtIndexPath中。我已經更新了答案,以更清楚地說明它的工作原理。 – chedabob

+0

Nop,它不起作用,我的意思是,hud出現,除了任務完成之後的任何其他想法? – Renexandro