How do you pass typedef'd blocks as params to a block that itself is a parameter to a method?

StackOverflow https://stackoverflow.com/questions/23685775

  •  23-07-2023
  •  | 
  •  

문제

I have a method that takes one parameter. This paramter is a block. This block itself takes two parameters, which are also blocks. They have the characteristic of returning void and accepting one argument that references an object.

For convenience let's typedef the blocks that are the parameters to the other block.

typedef void (^MyParamBlock)(id);

Then, the method that takes a block looks something like

[self someMethod:^(MyParamBlock pBlock1, MyParamBlock pBlock2) {
  // . . .
}

How do you create MyParamBlocks to pass to the method? The following view controller code is an example. The MyParamBlocks pb1 and pb2 do not get passed to the call to someMethod.

//
//  ViewController.m
//  PassingBlocksAsParamsToABlock

#import "ViewController.h"

typedef void (^MyParamBlock)(id);

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    MyParamBlock pb1 = ^(id obj) {
        NSLog(@"%@", obj);
    };

    MyParamBlock pb2 = ^(id obj) {
        NSLog(@"%@", obj);
    };

    [self someMethod:^(MyParamBlock pb1, MyParamBlock pb2) {
        NSString *str = @"strng";
        NSLog(@"%@", str);
        pb1(str);
        pb2(str);
    }];
}

- (void)someMethod:(void(^)(MyParamBlock, MyParamBlock))block
{
    NSLog(@"hallo");

    id pb1 = ^(id value) {
        // . .
    };

    id pb2 = ^(id anotherValue) {
        // . .
    };

    block(pb1, pb2);
}


@end
도움이 되었습니까?

해결책 2

(From my above comment:) You don't pass pb1, pb2 to someMethod:, it is exactly the other way around: someMethod: passes two blocks as arguments when calling the block that you passed to someMethod:.

다른 팁

Your current version of someMethod takes a block that takes two MyParamBlocks.

- (void)someMethod:(void(^)(MyParamBlock, MyParamBlock))block

You probably want this...

- (void)someMethodWithFirstBlock:(MyParamBlock)firstBlock secondBlock:(MyParamBlock)secondBlock

Or maybe...

- (void)someMethodWithParameterBlocks:(NSArray *)parameterBlocks; //of MyParamBlocks
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top