Declare a block method parameter without using a typedef

Objective CParametersObjective C-Blocks

Objective C Problem Overview


Is it possible to specify a method block parameter in Objective-C without using a typedef? It must be, like function pointers, but I can't hit on the winning syntax without using an intermediate typedef:

typedef BOOL (^PredicateBlock_t)(int);
- (void) myMethodTakingPredicate:(PredicateBlock_t)predicate

only the above compiles, all these fail:

-  (void) myMethodTakingPredicate:( BOOL(^block)(int) ) predicate
-  (void) myMethodTakingPredicate:BOOL (^predicate)(int)

and I can't remember what other combinations I've tried.

Objective C Solutions


Solution 1 - Objective C

- ( void )myMethodTakingPredicate: ( BOOL ( ^ )( int ) )predicate

Solution 2 - Objective C

This is how it goes, for example...

[self smartBlocks:@"Pen" youSmart:^(NSString *response) {
        NSLog(@"Response:%@", response);
    }];


- (void)smartBlocks:(NSString *)yo youSmart:(void (^) (NSString *response))handler {
    if ([yo compare:@"Pen"] == NSOrderedSame) {
        handler(@"Ink");
    }
    if ([yo compare:@"Pencil"] == NSOrderedSame) {
        handler(@"led");
    }
}

Solution 3 - Objective C

http://fuckingblocksyntax.com

As a method parameter:

- (void)someMethodThatTakesABlock:(returnType (^)(parameterTypes))blockName;

Solution 4 - Objective C

Another example (this issue benefits from multiple):

@implementation CallbackAsyncClass {
void (^_loginCallback) (NSDictionary *response);
}
// …


- (void)loginWithCallback:(void (^) (NSDictionary *response))handler {
    // Do something async / call URL
    _loginCallback = Block_copy(handler);
    // response will come to the following method (how is left to the reader) …
}

- (void)parseLoginResponse {
    // Receive and parse response, then make callback
    
   _loginCallback(response);
   Block_release(_loginCallback);
   _loginCallback = nil;
}


// this is how we make the call:
[instanceOfCallbackAsyncClass loginWithCallback:^(NSDictionary *response) {   // respond to result}];

Solution 5 - Objective C

Even more clear !

[self sumOfX:5 withY:6 willGiveYou:^(NSInteger sum) {
    NSLog(@"Sum would be %d", sum);
}];

- (void) sumOfX:(NSInteger)x withY:(NSInteger)y willGiveYou:(void (^) (NSInteger sum)) handler {
    handler((x + y));
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBogatyrView Question on Stackoverflow
Solution 1 - Objective CMacmadeView Answer on Stackoverflow
Solution 2 - Objective CMohammad AbdurraafayView Answer on Stackoverflow
Solution 3 - Objective CfunrollView Answer on Stackoverflow
Solution 4 - Objective CbshirleyView Answer on Stackoverflow
Solution 5 - Objective CHemangView Answer on Stackoverflow