Ответ 1
- ( void )myMethodTakingPredicate: ( BOOL ( ^ )( int ) )predicate
Можно ли указать параметр блока метода в 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)
и я не могу вспомнить, какие другие комбинации я пробовал.
- ( 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");
}
}
В качестве параметра метода:
- (void)someMethodThatTakesABlock:(returnType (^)(parameterTypes))blockName;
Другой пример (этот вопрос выгоден от нескольких):
@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
}];
Еще более ясно!
[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));
}