block的使用

Block是一个C语言的特性,它就是C语言的函数指针,在使用中最多的就是进行函数回调或者事件传递,比如发送数据到服务器,等待服务器反馈是成功还是失败,此时block就派上用场了.

基本语法

As a local variable:

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

As a property:

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

As a method parameter:

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

As an argument to a method call:

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

As a typedef:

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

代码示例

#import "ViewController.h"
@interface ViewController ()

@property (nonatomic, assign) void (^block)(NSString *);

@end

typedef void (^block)(NSString *);
typedef NSString *(^block2)(NSString *);

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    int (^num)(int) = ^(int a) {

        return a * 6;
    };
    NSLog(@"%d", num(5));

    block b = ^(NSString *string) {

        NSLog(@"%@", string);
    };
    b(@"4677646974");

    block2 b2 = ^(NSString *string) {
        NSLog(@"%@", string);
        return string;
    };
    NSLog(@"%@", b2(@"456"));

    [self methodsBlock:^(NSString *block3) {

        NSLog(@"%@", block3);
    }];

    [self methodsBlock2:^NSString *(NSString *block4) {

        NSLog(@"%@", block4);
        return @"1";
    }];
    NSLog(@"%@", [self methodsBlock3:^NSString *(NSString *block5) {
        NSLog(@"%@", block5);
        return @"2";
    }]);

    int (^num2)(int, int, int, int, int, int, int) = ^(int a, int b, int c, int d, int e, int f, int g) {

        return a * b * c * d * e * f * g;
    };
    NSLog(@"num2 = %d", num2(10, 2, 5, 1, 45, 4, 4));


}

- (void)methodsBlock:(void(^)(NSString *))block3 {

    block3(@"block3");
}


- (void)methodsBlock2:(NSString *(^)(NSString *))block4 {

    block4(@"block4");
    NSLog(@"%@", block4(@"block4"));
}


- (NSString *)methodsBlock3:(NSString *(^ __nullable)(NSString *))block5 {

    block5(@"block5");
    NSLog(@"block5 = %@", block5(@"block5"));
    return @"block5";
}
@end