do some work in the background and return the result do some work in the background and return the result multithreading multithreading

do some work in the background and return the result


It is possible, however the problem with returning a string from that function is that it would need to hold up your calling thread whilst you perform the work in the background - thus losing the benefit of the background thread. (dispatch_sync is what you would use to do that - however I would not recommend it).

When using blocks it is best to restructure your program to fit better with the asynchronous paradigm. When the work is complete it should notify whatever is waiting on the result by sending a message to it with the result. In your example you would put this in the block of code you dispatch on the main queue.

@interface TagManager- (void)fetchTag;- (void)tagFetched:(NSString *)tag;@end@implementation TagManager- (void)fetchTag {    // The following method does all its work in the background    [someObj readTagWithObserver:self];    // return now and at some point someObj will call tagFetched to let us know the work is complete}- (void)tagFetched:(NSString *)tag {    // The tag read has finished and we can now continue}@end

Then your readTag function would be modified as so:

- (void)readTagWithObserver:(id)observer {    ...    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{        ...        dispatch_async(dispatch_get_main_queue(), ^{           if (tag is ok) {                [observer tagFetched:tag];           }        });    });                          }

The main idea is that you need to split your processing up into two stages

  1. requesting that some work is done (fetchTag in my example)
  2. process the result when it finishes (tagFetched: in my example)