JackyW
JackyW

Reputation: 365

Proper thread handling

I've come to a problem where proper threading is needed, but I can't seem to optimise it correctly.

Here's my method:

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

inside [self refreshTableSessionList:xx], there's a

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)

to get data from server database, then a

dispatch_async(dispatch_get_main_queue(),

to populate and reload tableViewCell.

But there'll be a conflict for when I put a

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)

before [alloc database etc stuffs and retrieving of data here] and put dispatch_async(dispatch_get_main_queue(), when greying out the button, but that's inside a loop, which i don't think it is the right way.

What's the solution to overcome this?

Upvotes: 0

Views: 64

Answers (1)

Vladimir Vlasov
Vladimir Vlasov

Reputation: 2090

As I understood you don't wait for the finish of the background database stuff.

Have you read about multithreading? For example, Ray's article.

In a simple way, you can call dispatch_async inside the dipatch_async block inside the dispatch_async and etc.

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
  });
});

So you should switch between the main thread and a global queue. Also, you can use delegates, notifications or even reactivity for such purposes.

Upvotes: 1

Related Questions