-1

I have a method that creates a block inside. Is it possible to return the result of the method from this block? Something like:

- (id)myFunction {
     //some code here
     BlockType myBlock = ^{
           //some other code here
           return someObject; //is it possible to return something for myFunction?
     };
     [someOtherObject methodWithBlock: myBlock];
}
4

1 回答 1

1

Blocks can have a return type. Here's an example.

First you define a block type (optional, but convenient)

typedef NSString * (^BlockType)(NSString *name);
        ^^^^^^^^^^   ^^^^^^^^^  ^^^^^^^^^^^^^^
       return type   type name    parameters

Then you can instantiate a block like follows

BlockType aBlock = ^ NSString * (NSString *name){
    return [@"Hello " stringByAppendingString:name];
};

And use it

NSString *salutation = aBlock(@"Nikita");
NSLog(@"%@", salutation); // => Hello Nikita
于 2013-10-25T15:44:59.347 回答