block 应用说明
一、Block定义
Block可以理解为一个函数指针(即它是一个指针,指向某个函数)
returnType (^blockName) (parameter list) = ^ (parameter list) {代码块};
说明:
returnType:block的返回类型,可定义为void;
blockName:block的命名,可根据不同的变量/函数命名规范进行命名;
parameter list:block形参类型定义,可传入多个值,也可没有参数;
二、Block作为函数参数传递
returnType (^blockName) (parameter list)
说明:
returnType:block的返回类型,可定义为void;
blockName:block的命名,可根据不同的变量/函数命名规范进行命名;
parameter list:block形参类型定义,可传入多个值,也可没有参数;
实际声明方式:
+ (void)updateImage:(void(^)(NSInteger status,NSDictionary *res))block;
举例说明:
(1)定义无参无返回值的Block void (^printBlock)() = ^(){ printf("no number"); }; printBlock(); void (^myBlock)(NSString *); //block 声明 - (void)viewDidLoad { (1)block 在代码中的实现 myBlock = ^(NSString *text){ NSLog(@"my text = %@", text); }; (2)调用block函数的实现 int nCount = myCount(10, 5); NSLog(@"count = %zi", nCount); } //block函数原型定义 int (^myCount)(int a, int b) = ^(int a, int b) { return a+b; };
//变更网络请求方式 -(void)ModifyRequestMode:(void(^)())block { //取消所有任务,放到全局队列中优先级最高 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ ZLBAFHTTPClient *httpClient = [ZLBAFHTTPClient shareClient]; //取消队列中的所有网络请求任务 [httpClient cancelAllTasks]; //取消队列中所有任务 [httpClient.workQueue cancelAllOperations]; //重新匹配正确的CDN节点 [[ZLBGlobal sharedGlobal] changeNetwork:^{ block(); }]; }); } - (RACDisposable *)subscribeNext:(void (^)(id x))nextBlock completed:(void (^)(void))completedBlock { NSCParameterAssert(nextBlock != NULL); NSCParameterAssert(completedBlock != NULL); RACSubscriber *o = [RACSubscriber subscriberWithNext:nextBlock error:NULL completed:completedBlock]; return [self subscribe:o]; }
posted on 2019-07-09 07:06 东方🐺 阅读(223) 评论(0) 编辑 收藏 举报