Reputation: 444
I think I'm having a brain fog day... But is it possible to pass back a block from within a block?
For example:
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);
}
Here's what I got, but it looks really ugly:
- (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);
}
In short, the goal is to execute the first block and analyze the callback from that block. Then, pass the first block as a parameter to the second block.
Upvotes: 1
Views: 53
Reputation: 299265
The answer to the question as asked is very straight-forward, but I suspect that it isn't really your question. Nothing in your question suggests async behavior, but you keep saying "completion block." Getting results from non-async blocks is just a matter of returning their result:
// 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);
}
Is this really what you mean? (I suspect that making this abstract with "some block" and the like is making it much more complex than it really is and that you really mean to ask some related question rather than this one. And I think you mean "execute" when you say "implement.")
Upvotes: 1