Andrew White
Andrew White

Reputation: 169

Objective-C running loop in background while keeping UI functional?

How can I run a loop in the background such as:

while(1==1){
  NSLog(@"hello");
}

while being able to detect a button click such as:

- (IBAction)button:(id)sender {
    //do something
  }

Upvotes: 0

Views: 381

Answers (2)

william205
william205

Reputation: 688

You can use GCD to run the code on a background thread.

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul);
dispatch_async(queue, ^{

});

Upvotes: 1

CRD
CRD

Reputation: 53010

Read Apple's Concurrency Programming Guide and maybe Threading Programming Guide.

The first of these will introduce you to operation queues (NSOperation) and dispatch queues (GCD), the second to threads (NSThread & Posix).

If after reading the guide you are unsure which of the approaches to take, at least for the situation you raise above, consider GCD first and then operation queues.

If you get stuck implementing your solution ask a new question, showing your code and explaining your issues. Somebody will undoubtedly help you out.

HTH

Upvotes: 0

Related Questions