2017-03-17 142 views
0

我来这里是正确的需要螺纹的问题,但我似乎不能正确地优化它。正确的线程处理

这里是我的方法:

-(void) method1 
{ 
    // -1 to an NSInteger 
    nsint1--; 

    [self showActiviyIndicator:YES]; //act as loading screen 

    [alloc database etc stuffs and retrieving of data here] 

    //for loop here to check with database, and grey out button depending on database values 
    for (int i = 1; i<12; i ++) 
    { 
    //get values from database and store into variables, then grey out the button if variables are 0. 
    } 

    int Val1 = [get from database] 

    if Val1 = 0 
    [button setTitleColor:[UIColor Grey]]; 

    someLabel.text = [NSString stringWithFormat:@"%ld", (long)nsint1]; 

    //here's where the problem lies 
    [self refreshTableSessionList:xx]; 

    [self showActiviyIndicator:NO] 
} 

内[自refreshTableSessionList:XX],有一个

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0) 

从服务器数据库获取数据,然后

dispatch_async(dispatch_get_main_queue(), 

填充并重新加载tableViewCell。

但是这样会有当我把一个

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0) 

[alloc database etc stuffs and retrieving of data here] 前变灰的按钮时把dispatch_async(dispatch_get_main_queue(), 冲突,但是这是一个循环中,我不认为这是正确的办法。

什么是克服这种解决办法吗?

+0

使用块从服务器数据库获取数据。 – Kampai

+0

你的循环在哪里? – 2017-03-17 07:37:17

+0

的可能的复制[iPhone - 大中央调度主线程(http://stackoverflow.com/questions/7905192/iphone-grand-central-dispatch-main-thread) – 2017-03-17 07:39:37

回答

1

我了解你不等待的后台数据库的东西终点。

你看了关于多线程?例如,Ray's article

在一个简单的方法,你可以调用dispatch_async的dispatch_async内dipatch_async块内等

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
    // do some database stuff 
    dispatch_async(dispatch_get_main_queue(), ^{ 
    // do some UI stuff 
    }); 
}); 

所以,你应该在主线程和全局队列之间进行切换。此外,您可以使用代表,通知甚至反应性来达到此目的。

+0

这很好,你想帮忙,但是请避免回答以前已经回答过100次的问题。如果您觉得合适,请将其标记为重复。 – 2017-03-17 07:40:12

+0

感谢您的链接,现在看看它,以及雷的块教程。谢谢。 – JackyW