htzfun
htzfun

Reputation: 1448

Wait for return in multithreading

I got class with method that wraps work with twitter api. I understand that I should use threads to work with Internet. But I'm a little bit new in this part of programming. So I decided that this would be enough.

-(NSArray*) getTweets:(NSString *)query {
     [self performSelectorOnMainThread:@selector(anotherMethod:) withObject:query waitUntilDone:YES];
     return [self tweets];
}

And that's how I call it in main method:

NSString* query = @"query";
id<TwitterGetter> obj = [[className alloc] init];
NSArray* array = [obj getTweets:query];

But NSArray* is nil after this. What should I do to avoid this problem? I tried to read guides from apple, but looks like I didn't get it.

Upvotes: 0

Views: 89

Answers (1)

Matic Oblak
Matic Oblak

Reputation: 16794

To understand what exactly is going on we would need quite a lot more code, know what thread you are calling this on... Anyway, rather try some callback procedure. In your case anotherMethod: should call some callback method on main thread with your array parameter.

For instance this should be a good approach:

- (void)buttonPressed:(id)sender {
    //start some spinner or continue with application
    //even some locking mechanism might be needed so this method is not called multiple times
    [self getTweets:@"whatever"];
}
- (void)getTweets:(NSString *)query {
    [self performSelectorInBackground:@selector(anotherMethod:) withObject:query];
}
- (void)anotherMethod:(NSString *)query {
    //get tweets
    NSArray *tweets;
    [self performSelectorOnMainThread:@selector(gotTweets:) withObject:tweets waitUntilDone:NO];
}
- (void)gotTweets:(NSArray *)tweets {
    //stop the spiner if needed
    //unlock if needed
    //do whatever with your data
}

About synchronisation:

You should always avoid doing loading and waiting on the main thread. If you need the screen to pause try adding some overlay (usually with some low alpha) and possibly add an UIActivityIndicatorView so the user can see some loading is in progress and block user interaction so he can not proceed into the application. Note if you are blocking the main thread for too long your application will be terminated (called watchdog) that is the main reason why you should do all the loading and requesting on a separate thread. Well, beside the reason the user may think the application is stuck and might kill it.

Upvotes: 2

Related Questions