是否可以在不使用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)
我不记得我尝试过的其他组合。
答案 0 :(得分:235)
- ( void )myMethodTakingPredicate: ( BOOL ( ^ )( int ) )predicate
答案 1 :(得分:63)
这是怎么回事,例如......
[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");
}
}
答案 2 :(得分:18)
作为方法参数:
- (void)someMethodThatTakesABlock:(returnType (^)(parameterTypes))blockName;
答案 3 :(得分: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
}];
答案 4 :(得分: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));
}