iphone ios running in separate thread

IphoneMultithreadingIosThread Safety

Iphone Problem Overview


What is the best way to run code on a separate thread? Is it:

[NSThread detachNewThreadSelector: @selector(doStuff) toTarget:self withObject:NULL];

Or:

	NSOperationQueue *queue = [NSOperationQueue new];
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self
																		selector:@selector(doStuff:)
																		  object:nil;
[queue addOperation:operation];
[operation release];
[queue release];

I've been doing the second way but the Wesley Cookbook I've been reading uses the first.

Iphone Solutions


Solution 1 - Iphone

In my opinion, the best way is with libdispatch, aka Grand Central Dispatch (GCD). It limits you to iOS 4 and greater, but it's just so simple and easy to use. The code to do some processing on a background thread and then do something with the results in the main run loop is incredibly easy and compact:

dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    // Add code here to do background processing
    //
    //
    dispatch_async( dispatch_get_main_queue(), ^{
        // Add code here to update the UI/send notifications based on the
        // results of the background processing
    });
});

If you haven't done so already, check out the videos from WWDC 2010 on libdispatch/GCD/blocks.

Solution 2 - Iphone

The best way for the multithreading in iOS is using GCD (Grand Central Dispatch).

//creates a queue.

dispatch_queue_t myQueue = dispatch_queue_create("unique_queue_name", NULL);

dispatch_async(myQueue, ^{
    //stuffs to do in background thread
    dispatch_async(dispatch_get_main_queue(), ^{
    //stuffs to do in foreground thread, mostly UI updates
    });
});

Solution 3 - Iphone

I would try all the techniques people have posted and see which is the fastest, but I think this is the best way to do it.

[self performSelectorInBackground:@selector(BackgroundMethod) withObject:nil];

Solution 4 - Iphone

I have added a category on NSThread that will let you execute threads in blocks with ease. You can copy the code from here.

https://medium.com/@umairhassanbaig/ios-how-to-perform-a-background-thread-and-main-thread-with-ease-11f5138ba380

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMike SView Question on Stackoverflow
Solution 1 - IphoneJacquesView Answer on Stackoverflow
Solution 2 - IphoneKusal ShresthaView Answer on Stackoverflow
Solution 3 - IphoneBobbyView Answer on Stackoverflow
Solution 4 - IphoneUmairView Answer on Stackoverflow