在不使用typedef的情况下声明块方法参数

Bog*_*tyr 143 parameters objective-c objective-c-blocks

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

typedef BOOL (^PredicateBlock_t)(int);
- (void) myMethodTakingPredicate:(PredicateBlock_t)predicate
Run Code Online (Sandbox Code Playgroud)

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

-  (void) myMethodTakingPredicate:( BOOL(^block)(int) ) predicate
-  (void) myMethodTakingPredicate:BOOL (^predicate)(int)
Run Code Online (Sandbox Code Playgroud)

我不记得我尝试过的其他组合.

Mac*_*ade 237

- ( void )myMethodTakingPredicate: ( BOOL ( ^ )( int ) )predicate
Run Code Online (Sandbox Code Playgroud)

  • +1,虽然`typedef`应该更适合更复杂的情况. (9认同)
  • 这些只是参数名称.只需使用它们. (6认同)
  • ` - (void)myMethodTakingPredicate:(BOOL(^)(NSString*name,NSString*age))predicate {//我应该如何在这里访问姓名和年龄......?}` (3认同)
  • 强烈推荐!命名您的变量。它们将自动完成为可用代码。因此,将BOOL(^)(int)替换为BOOL(^)(int count)。 (2认同)

Moh*_*fay 65

这就是它的方式,例如......

[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");
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 没什么特别的.我只是习惯使用'compare:'.'[NSString isEqualToString:]'是一种更好的方法. (2认同)

fun*_*oll 19

http://fuckingblocksyntax.com

作为方法参数:

- (void)someMethodThatTakesABlock:(returnType (^)(parameterTypes))blockName;
Run Code Online (Sandbox Code Playgroud)


bsh*_*ley 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
}];
Run Code Online (Sandbox Code Playgroud)