声明一个块方法参数,而不使用typedef

是否可以在不使用typedef的情况下在Objective-C中指定方法块参数? 它必须像函数指针一样,但是我不能在不使用中间typedef的情况下赢得胜利的语法:

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

只有上面的编译,所有这些失败:

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

我不记得我试过的其他组合。

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

例如,这是怎么回事

 [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"); } } 

http://fuckingblocksyntax.com

作为方法参数:

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

另一个例子(这个问题从多重收益):

 @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 }]; 

更清楚!

  [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)); }