1

I have a bit of code as follows:

companyLogo = nil;


[DLImageLoader loadImageFromURL:image_url
                      completed:^(NSError *error, NSData *imgData) {
                          if (error == nil) {

                              __block UIImage *companyLogo = [UIImage imageWithData:imgData];

                          } else {
                              // if we got error when load image
                          }
                      }];

I am trying to assign the data that comes back from the DLImageLoader block to companyLogo. How would I do this?

stackOverFlew
  • 1,479
  • 2
  • 31
  • 58

2 Answers2

2

You simply define your local variable with the __block keyword.

__block UIImage* companyLogo = nil;

[DLImageLoader loadImageFromURL:image_url
                      completed:^(NSError *error, NSData *imgData) {
                          if (error == nil) {
                              companyLogo = [UIImage imageWithData:imgData];
                          } else {
                              // if we got error when load image
                          }
                      }];

In the example you posted, you were redeclaring the variable inside the block, therefore "hiding" the variable declared outside the block. Instead, we declare it once (outside the block), and add the __block keyword to indicate that we want this variable to be persistently modifiable inside the block.

You can read more about the logistics of the __block keyword here: What does the "__block" keyword mean?. Essentially it tells the compiler on how to deal with the memory management of the variable, so that the true memory location of the variable is visible inside the block, instead of a copy of the contents of the variable.

Community
  • 1
  • 1
WDUK
  • 18,870
  • 3
  • 64
  • 72
  • This answer is useless, because the method `loadImageFromURL:completed:` is asynchronous, and so outside the block, the local variable `companyLogo` cannot be set before the current function returns. – newacct Feb 08 '14 at 21:56
0

I believe you need to add __block to company logo as well. Get rid of the declaration/assignment in your block and use the first one. :)

bobber205
  • 12,948
  • 27
  • 74
  • 100