从块内回调块

时间:2018-05-23 01:39:27

标签: ios objective-c

我想我有一个脑雾日...但是有可能从一个街区内传回一个街区吗?

例如:

typedef void(^SomeBlock)(int someValue);
typedef void(^SomeOtherBlock)(int someOtherValue, SomeBlock originalBlock); // how would you pass SomeBlock?


- (void)getSomeValue:(SomeOtherBlock)completionBlock {
  [self someMethod:^(int someValue){
    // How could I call SomeOtherBlock & pass back SomeBlock?
    int someOtherValue = 2;
    // I.e, completionBlock(someOtherValue, SomeBlock);
  }];
}
- (void)someMethod:(SomeBlock)completionBlock {
  completionBlock(1);
}

这是我得到的,但它看起来很丑陋:

- (void)getSomeValue:(SomeOtherBlock)completionBlock {
  [self someMethod:^(int someValue) {
    int someOtherValue = 2;
    SomeBlock someBlock = ^(int innerVal) {
      innerVal = someValue;
    };
    completionBlock(someOtherValue, someBlock);
  }];
}
- (void)someMethod:(SomeBlock)completionBlock {
  completionBlock(1);
}

简而言之,目标是执行第一个块并分析该块的回调。然后,将第一个块作为参数传递给第二个块。

1 个答案:

答案 0 :(得分:1)

问题的答案是非常简单的,但我怀疑这不是你的问题。你的问题中没有任何内容暗示异步行为,但你一直在说"完成块。"从非异步块获取结果只是返回结果的问题:

// SomeBlock takes an int and returns an int
// (In your example you have it return void, but then what is "analyzed?"
typedef int(^SomeBlock)(int someValue);

// SomeOtherBlock takes an int and also a SomeBlock
typedef void(^SomeOtherBlock)(int someOtherValue, SomeBlock originalBlock);


void executeAnalyzeAndContinue(SomeBlock firstBlock, SomeOtherBlock secondBlock, int value) {
    // execute the first block
    int result = firstBlock(value);

    // and analyze the callback (return value?) from that block. 
    if (result == 2) { NSLog(@"%@", @"It was two"); }

    // Then, pass the first block as a parameter to the second block (and also a value?)
    secondBlock(result, firstBlock);
}

这真的是你的意思吗? (我怀疑使用"某些块"等等使它变得比实际上复杂得多,并且你真的想要问一些相关问题而不是这个问题。而且我认为你的意思是"执行"当你说'#34;实施。")