2013-10-08 37 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