Git.Coach
Git.Coach

Reputation: 3092

Alternative methods to receive return value from a (former) function running in separate NSThread?

I've started refactoring my code recently and I'm trying to increase performance by using more threads. Especially for downloads and connections. I've had a function called...

- (UIImage *)imageFromURLString:(NSString *)urlString;

...which just establishes a connection, creates an UIImage from the received data und returns it.

Now I've started working with threads and I realized that I can't get a return value (which makes sense as the thread runs separatly from the method it is been called from). What would be the "best" / most elegant way, to solve problems of this kind in general?

I'm aware that using a class variable would be the easiest solution, but it doesn't seem very "clean" nor optimal to me. Thanks in advance!

Upvotes: 0

Views: 105

Answers (1)

Ultrakorne
Ultrakorne

Reputation: 1303

the answer is blocks

- (void)imageFromURLString:(NSString *)urlString completionBlock:(void(^)(UIImage *image))

basically when the image is fetched, you will execute the block passed by the callee and the image will be passed as an arg

the usage will be

[self imageFromURLString:@"url" completionBlock:^(UIImage *image){
    //do some stuff with the image
}

Upvotes: 3

Related Questions