不使用typedef声明块方法参数

148

在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)

而我记不得我尝试过哪些其他组合。


3
http://goshdarnblocksyntax.com/ - Kyle Clegg
5个回答

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

9
+1,尽管对于更复杂的情况,应该优先考虑使用typedef。 - Fred Foo
3
- ( void )myMethodTakingPredicate: ( BOOL ( ^ )( NSString *name, NSString *age ) )predicate { //How Should I Access name & age here...? } - Mohammad Abdurraafay
6
那些只是参数名称,请直接使用它们。 - Macmade
1
唉,这个语法一点也不直观。:( - devios1
3
强烈推荐命名你的变量,这将使它们自动完成成可用的代码。因此,请用BOOL (^)(int count)替换BOOL (^) (int) - funroll
显示剩余4条评论

67

比如说,它是这样运行的...

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

你为什么不使用[NSString isEqualToString:]方法? - orkoden
2
没有具体的事情。我只是习惯经常使用 'compare:'。不过 '[NSString isEqualToString:]' 是更好的方式。 - Mohammad Abdurraafay
smartBlocks 方法定义中,你需要单独使用 response 这个词吗?难道不可以直接写成 (NSString*))handler { 吗? - Ash
你也可以使用 (NSString *)) handler。这也是有效的。 - Mohammad Abdurraafay

20

9
另一个例子(这个问题受益于多方面):
@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
}];

2

更加清晰明了!

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接