Reputation: 2703
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
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.
returnType (^blockName)(parameterTypes) = ^returnType(parameters) {...};
@property (nonatomic, copy) returnType (^blockName)(parameterTypes);
- (void)someMethodThatTakesABlock:(returnType (^)(parameterTypes))blockName;
[someObject someMethodThatTakesABlock:^returnType (parameters) {...}];
typedef returnType (^TypeName)(parameterTypes);
TypeName blockName = ^returnType(parameters) {...};
You would just replace returnType
with void
.
Upvotes: 5
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