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)
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)
fun*_*oll 19
作为方法参数:
- (void)someMethodThatTakesABlock:(returnType (^)(parameterTypes))blockName;
Run Code Online (Sandbox Code Playgroud)
另一个例子(这个问题得益于多个):
@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)