开发者

Call inline block specifying return Type and Parameters

开发者 https://www.devze.com 2023-04-02 08:30 出处:网络
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 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 ta开发者_JS百科kes 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]}


The problem is that your method declaration expects a block returning void (nothing):

- (void) ifTrueDo: (void (^) ()) trueBlock 
        ifFalseDo: (void (^) ()) falseBlock;

However, you later call this passing in blocks with the signature of (id^()()):

[condition ifTrueDo:(id (^)()) {
    NSLog(@"True");
}         ifFalseDo:(id (^)()) {
    NSLog(@"False");
}];

Just get rid of the "id" part like the following - note: and I tried this and it compiles without warnings:

[condition ifTrueDo:^{
          NSLog(@"True");
     }
     ifFalseDo:^{
          NSLog(@"False");
     }
 ];
0

精彩评论

暂无评论...
验证码 换一张
取 消