不使用 typedef 声明块方法参数

是否可以在 Objective-C 中指定一个方法块参数而不使用 typedef?它必须像函数指针一样,但是如果不使用中间 typedef,我就无法找到正确的语法:

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

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

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

我不记得我还试过什么组合了。

90738 次浏览
- ( 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");
}
}

另一个例子(这个问题受益于多个) :

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

Http://fuckingblocksyntax.com

作为方法参数:

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

更清楚了!

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