0

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?

  • Should I just create an atomic class variable and fill it from within the former function?
  • Maybe passing a pointer to an UIImage object to the method and fill it from within?

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!

Git.Coach
  • 3,032
  • 2
  • 37
  • 54

1 Answers1

3

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
}
Ultrakorne
  • 1,303
  • 11
  • 18
  • 1
    I didn't think about them. Thanks for this hint. So I should basically save the image from within the block? – Git.Coach Feb 27 '13 at 09:15
  • depend on what you need to do. you can pass the arg to another method that process the image. but yes if you need to keep that image you can keep a reference to it – Ultrakorne Feb 27 '13 at 10:56