2

I'm trying to understand blocks a bit more.

I have these definitions:

@property (nonatomic, retain) NSMutableArray * callBacksOnSuccess;
@property (nonatomic, copy) void (^callBackSuccessWithUIImage) (UIImage *) ;

When the image download finishes I do this in the completion block and things are fine

UIImage *coverImage = [UIImage imageWithData:data];
callBackSuccessWithUIImage(coverImage);

Now I'd like to be able to do same for all callback blocks stored in the callBacksOnSuccess NSMutableArray but I don't know how to approach this.

I'm trying a for in loop, but that's not working most likely because of the ambigous id class definition:

UIImage *coverImage = [UIImage imageWithData:data];
for (id callBackBlock in callBacksOnSuccess) 
{callBackBlock(coverImage);}

Please push me towards the right approach.

thank you!

1 Answer 1

3

First of all:

Consider to use a typedef to your blocks, in order to ease the syntax:

typedef void (^MyBlock)(UIImage*); //declare this somewhere

Then, you can easily iterate through your array like this, executing each block inside it:

UIImage *coverImage = [UIImage imageWithData:data];
for (MyBlock block in callBacksOnSuccess) {
    block(coverImage);
}

You can even use the new type in your property:

@property (nonatomic, copy) MyBlock callBackSuccessWithUIImage;
Sign up to request clarification or add additional context in comments.

3 Comments

thank you! works like a charm. so surprised to see typedef as the solution.
Glad to help! The typedef actually just made everything much easier to understand and read. Your problem was because you were declaring the callBackBlock variable inside the foreach loop as the type of id, who does not support calls like block(). If you had declared the variable as void (^callBackBlock) (UIImage *) in the for loop, it would have worked in the same way, but just a lot 'uglier'
yes, I knew the id was the problem, just couldn't figure out what to do about it. Blocks are awesome, I just need a bit more time to understand them fully.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.