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?
-
http://goshdarnblocksyntax.com/ – TylerP Jul 20 '15 at 03:45
-
http://stackoverflow.com/questions/13193673/how-do-i-create-an-objective-c-method-that-return-a-block – isaced Jul 20 '15 at 03:51
-
Go through this, I hope you will get to know https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/WorkingwithBlocks/WorkingwithBlocks.html – Janmenjaya Jul 20 '15 at 04:00
-
+ before a function makes it a class method instead of an instance method, aka static vs non-static functions – Fonix Jul 20 '15 at 04:48
2 Answers
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
.

- 1,855
- 1
- 14
- 20
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

- 162
- 1
- 12