timpone
timpone

Reputation: 19969

How to declare a method that takes a block as a callback

I have a method that I'd like to call like so:

  void (^someblock)()=^{
    NSLog(@"I want to know");
  };
  [Item getCacheAndCallback:self.menuItemID andCallback:someblock];

How would I declare this in my header file? I have tried

  +(void)getCacheAndCallback:(int)menuItemID andCallback:(^());

but says "Expected a type". I thought this was supposed to go to void for type.

Upvotes: 0

Views: 61

Answers (3)

Louis T
Louis T

Reputation: 1313

Block syntax is weird. I keep this link handy to reference any time I happen to forget something: fuckingblocksyntax.com

Upvotes: 1

CRD
CRD

Reputation: 53010

Putting block types directly into method signatures can get messy as you've found. I would suggest you use a typedef to make it cleaner:

typedef void(^VoidBlock)();

Now you can write your block declaration as:

VoidBlock someBlock =  ^{ NSLog(@"I want to know"); };

and your method declaration as:

+ (void) getCacheAndCallback:(int)menuItemID andCallback:(VoidBlock)callBack;

Note: that typedef does not introduce a new type, just a shorthand. This means, for example, that you can declare a block using the full type (or even a different typedef with the same full type) and use it as VoidBlock.

Upvotes: 1

Onik IV
Onik IV

Reputation: 5047

 +(void)getCacheAndCallback:(int)menuItemID andCallback:(void(^)(void))completionBlock;

Upvotes: 4

Related Questions