I've decided to try to use blocks for control flow in Objective-C and am running into some issues with calling multiple blocks inline.
I've got an OOBoolean which is a wrapper to a BOOL primitive, and provides these methods:
+ (id) booleanWithBool: (BOOL) boolPrimitive;
- (id) initWithBool: (BOOL) boolPrimitive;
- (void) ifTrueDo: (void (^) ()) trueBlock
ifFalseDo: (void (^) ()) falseBlock;
- (void) ifTrueDo: (void (^) ()) trueBlock;
- (void) ifFalseDo: (void (^) ()) falseBlock;
I have no problem using this class like so:
OOBoolean* condition = [OOBoolean booleanWithBool: (1 + 1 == 2)];
id trueBlock = ^(){
NSLog(@"True.");
};
id falseBlock = ^(){
NSLog(@"False.");
};
[condition ifTrueDo: trueBlock ifFalseDo: falseBlock];
And I get a result of "True.". But I keep getting syntax errors when trying this instead:
OOBoolean* condition = [OOBoolean booleanWithBool: (1 + 1 == 2)];
[condition ifTrueDo:(void (^)()) {
NSLog(@"True");
} ifFalseDo:(void (^)()) {
NSLog(@"False");
}];
Is it not possible to define multiple blocks anonymously and pass them to a method that takes multiple block arguments? If so, that's kind of a let down.
It's possible.
You simply had way too many parentheses in there. Try this:
[condition ifTrueDo:^() { NSLog(@"True"); }
ifFalseDo:^() { NSLog(@"False"); }
];
EDIT: Your block syntax is slightly incorrect.
If you want to include return type and parameters, you should use something closer to this:
[self ifTrueDo:^ void (void) { NSLog(@"True"); }
ifFalseDo:^ void (void) { NSLog(@"False"); }
];
In english:
^ [return type] ([parameter list]) {[block content]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With