无法访问在此方法中作为参数传递的块

时间:2017-09-04 19:27:29

标签: ios objective-c objective-c-blocks

在下面的例子中,我不知道如何访问我在方法中作为参数传递的块。我应该使用typedef,但只有当我破坏了代码时,我才能得到以下场景。所以没有使用typedef

@interface ViewController ()

- (void(^)(void))  anotherMethodWithReturnTypeAnd: ( void ( ^ )( int ))argumentsBlock;

@end

@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];

void (^twoBlock)(void) = [ self anotherMethodWithReturnTypeAnd:^(int n) {
    NSLog(@"%d, block without typedef",n);
}];
twoBlock();
}


- (void(^)(void))  anotherMethodWithReturnTypeAnd: ( void ( ^ )( int n) )argumentsBlock{
void (^blockToPassAsReturnType)(void) = ^{
    NSLog(@"Passing this block as return type");
};
return blockToPassAsReturnType;
}

输出:

2017-09-05 00:23:08.148 DeleteThisBlockProject[657:22195] Passing this block as return type

那么我应该如何使用和传递我作为参数传递的块的值,[self anotherMethodWithReturnTypeAnd:^(int n){         NSLog(@“%d,block without typedef”,n);     }];

1 个答案:

答案 0 :(得分:0)

你没有调用方法

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];

    void (^twoBlock)(void) = [ self anotherMethodWithReturnTypeAnd:^(int n) {
        // this will never execute because you didn't call it you just implemented it
        NSLog(@"%d, block without typedef",n); 
    }];
    twoBlock();
}


- (void(^)(void))  anotherMethodWithReturnTypeAnd: ( void ( ^ )( int n) )argumentsBlock{
    void (^blockToPassAsReturnType)(void) = ^{
        NSLog(@"Passing this block as return type");
    };
    // you should call method which you did provide to this function
    argumentsBlock(yourInt)
    return blockToPassAsReturnType;
}