0

how can i add this piece of code inside an asynchronous block which keeps on running in the background?

for(int i=0;i<10; i++){
        carRPM = [NSString stringWithFormat:@"%d",i];
        NSLog(@"Car RPM: %@",carRPM);
    }
Popeye
  • 11,839
  • 9
  • 58
  • 91
Adeel
  • 123
  • 13
  • 2
    Please be aware that none of your questions so far have had anything to do with the `xcode IDE` so please stop using that tag. – Popeye Mar 16 '15 at 12:12

2 Answers2

2

You would want to dispatch an asynchronous thread to execute your code from within a closure using the following syntax:

dispatch_queue_t myQueue = dispatch_queue_create("My Queue",NULL);
dispatch_async(myQueue ,^{
    for(int i=0;i<10; i++){
    carRPM = [NSString stringWithFormat:@"%d",i];
    NSLog(@"Car RPM: %@",carRPM);
    }

   dispatch_async(dispatch_get_main_queue(), ^{
    // Update the UI

   });
});

EDIT: Updated my code to be more accurate for running on a separate thread as well as added a block from within the thread to update UI as you update the UI via the main thread.

chrissukhram
  • 2,957
  • 1
  • 13
  • 13
  • 1
    No problem, I was assuming you were doing this in swift. I have approved your edits to convert the code to objective-c. Glad it worked out. If the question is complete and you see fit, please remember to accept the answer :). – chrissukhram Mar 16 '15 at 07:48
  • 3
    I thought the OP wanted this to execute in a background thread, not the main thread? – trojanfoe Mar 16 '15 at 08:07
  • @trojanfoe, good catch, I mistakenly pasted an example dispatching to the main queue. I have updated my answer to reflect this correctly. Thanks. – chrissukhram Mar 16 '15 at 15:47
0

You can create a separate thread to run your loop in by using GCD and using dispatch_async().

// Create the new thread that you want to run the loop on.
dispatch_queue_t myLoopQueue = dispatch_queue_create("My Loop Queue", NULL);
dispatch_async(myLoopQueue, ^{
    for(int i=0;i<10; i++) {
        carRPM = [NSString stringWithFormat:@"%d",i];
        NSLog(@"Car RPM: %@",carRPM);
    }
});

I'll assume that you will want to use the value stored within carRPM sooner or later. So it would be wise to know that the final value of carRPM will be lost once the thread is finished. To be able to use the final value of carRPM that has been set within the block you'll need to mark carRPM with the keyword __block, checkout the explanation of this keyword here.

If you just use dispatch_get_main_queue() this will run your loop on the main thread and NOT on a separate thread.

Community
  • 1
  • 1
Popeye
  • 11,839
  • 9
  • 58
  • 91