Jenel Ejercito Myers
Jenel Ejercito Myers

Reputation: 2703

Blocks with no return value

Is there a proper way to write a block with no return value in Objective-C? All the examples that I have seen are all with return values. Can someone also please explain the difference between a completion block & a regular block? I know the ^ means that it is a block but doesn't the + before (void) mean it is a block as well?

Upvotes: 1

Views: 3945

Answers (2)

Taylor M
Taylor M

Reputation: 1865

Here is what a method header would look like if it has a parameter of a block:

- (void)someMethodThatTakesABlock:(returnType (^)(parameterTypes))blockName;

So a block with no return type and no parameters would look something like this:

- (void)someMethodThatTakesABlock:(void (^)(void))blockName;

A regular block is just a set (or group) of code. A completion block is a block that will be executed when the method is completed. A completion block is a regular block, it just is specific to being called at the end of a method.

The ^ signifies a block. The + before a method is a class method.

Other ways to use blocks

As a local variable

returnType (^blockName)(parameterTypes) = ^returnType(parameters) {...};

As a property

@property (nonatomic, copy) returnType (^blockName)(parameterTypes);

As a method parameter

- (void)someMethodThatTakesABlock:(returnType (^)(parameterTypes))blockName;

As an argument to a method call

[someObject someMethodThatTakesABlock:^returnType (parameters) {...}];

As a typedef

typedef returnType (^TypeName)(parameterTypes);
TypeName blockName = ^returnType(parameters) {...};

You would just replace returnType with void.

Upvotes: 5

Scott
Scott

Reputation: 162

Here is a demo:
1、no return values and no parameter:

- (void)viewDidLoad {
[super viewDidLoad];

//block
void(^myBlock)(void)  = ^(void) {
    NSLog(@"This is a block without parameter and returned value");
};
myBlock();

2、no return values and have parameter:

-(void)blockWithParameterButNoReturnData
{
    void(^myBlock)(int) = ^(int num) {
        NSLog(@"%d",num*100);
    };
    myBlock(4);
}

3、have retrun values and have parameter: -(void)blockWithParameterAndReturnValue

{
    int (^myBlock)(int) = ^(int num) {
        return num * 100;
    };
   int result =  myBlock(2);
    NSLog(@"This is a block with parameter and return value :%d",result);
}

PS:for more infomation,see this website:http://www.cnblogs.com/zhanggui/p/4656440.html

Upvotes: 3

Related Questions