适当的线程处理

Proper thread handling

我遇到了一个问题,需要适当的线程,但我似乎无法正确优化它。

这是我的方法:

-(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]
}

在[self 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(), ,但这是在一个循环中,我认为这不是正确的方法。

克服这个问题的解决方案是什么?

据我了解,您无需等待后台数据库完成。

你读过多线程吗?例如,Ray's article.

一个简单的方法,你可以在 dipatch_async 块内调用 dispatch_async 在 dispatch_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
  });
});

所以你应该在主线程和全局队列之间切换。此外,您可以为此目的使用委托、通知甚至反应性。