KingPolygon
KingPolygon

Reputation: 4755

iOS: Background Threads / Multithreading?

If a second method is called from a method that is running on a background thread, is the second method automatically ran in that same thread or does it happen back on the main thread?

Note: I want my second method to be handled in the background, but since I update the UI inside it, would doing the following, be the right way to do it:

- (void)firstMethod {

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{

        //Do stuff in background
        ...

        //Call a second method (Assume it'll run in this background thread as well)
        [self secondMethod];
    });
}

//Second Method

- (void)secondMethod {

    //Do heavy lifting here
    ...

    dispatch_async(dispatch_get_main_queue(), ^{

        //Update UI here
        ...

    });
}

Update

Oh I totally forgot to mention that this method is something that loads suggestions into the view (think keyboard suggestions). Since every key tap would be calling this method, I only want it to run when a user has finished typing. The way I'm approaching it is by setting a 0.2 delay between keys and if a new key tap fall within that 0.2 delay it cancels the previous method call, and initiates a new call (this way, assuming the use types the word, "the", it doesn't run suggestions for "t", "th", "the". Since the user is typing pretty quickly we can assume they don't want suggestions for anything until they have stopped typing (allowing the call to go through after a 0.2s delay), or if they type slow (where they probably are looking for suggestions along the way).

So when calling my secondMethod I do the following:

[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(secondMethod) object:nil];
[self performSelector:@selector(secondMethod) withObject:nil afterDelay:0.2];

The problem is it's not being called (I'm assuming this method defaults it to be performed in the main thread?)

Upvotes: 1

Views: 741

Answers (1)

Catfish_Man
Catfish_Man

Reputation: 41801

Generally speaking, nothing is going to hop between threads without being pretty explicit about it. Certainly something as trivial as just calling a method isn't. Your code seems fine. Remember to not access mutable state from more than one queue at once (for example if the heavy lifting uses instance variables, make sure that -firstMethod doesn't get called twice in a row. It'd spawn off two async calls to -secondMethod then, and they'd step all over each others data. If that's a problem, create a serial dispatch queue instead of using a global one).

Upvotes: 2

Related Questions