block 应用说明

一、Block定义

Block可以理解为一个函数指针(即它是一个指针,指向某个函数)

returnType (^blockName) (parameter list) = ^ (parameter list) {代码块};
//returnType:block的返回类型,可定义为void;
//blockName:block的命名,可根据不同的变量/函数命名规范进行命名;
//parameter list:block形参类型定义,可传入多个值,也可没有参数;

举例说明:

//定义无参无返回值的Block
void (^printBlock)() = ^(){
  printf("no number");
};
printBlock();

void (^myBlock)(NSString *); //block 声明

- (void)viewDidLoad 
{
  //block 在代码中的实现
  myBlock = ^(NSString *text){
    NSLog(@"my text = %@", text);
  };
  //调用block函数的实现
  int nCount = myCount(10, 5);
  NSLog(@"count = %zi", nCount);
}

//block函数原型定义
int (^myCount)(int a, int b) = ^(int a, int b)
{
  return a+b;
};

二、Block作为函数参数传递

returnType (^blockName) (parameter list)
//returnType:block的返回类型,可定义为void; //blockName:block的命名,可根据不同的变量/函数命名规范进行命名; //parameter list:block形参类型定义,可传入多个值,也可没有参数;

实际声明方式:

+ (void)updateImage:(void(^)(NSInteger status,NSDictionary *res))block;

//变更网络请求方式
-(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];
}

 

实现简单的相应是block函数:

@property(nonatomic, strong) RACSubject *subject;

self.subject = [RACSubject subject]; //初始化信号

//响应式block回调
-(void)finishModel:(void(^)(void))block{
        //接收到信号后,返回block
    [self.subject subscribeNext:^(id  _Nullable x) {
        return block();
    }];
}

//动画结束后,发送完成信号
[UIView animateWithDuration:animalDuration animations:^{
        self.alphView.alpha = 0.0;
        self.bkView.frame = CGRectMake(0, kMainBoundsHeight, kMainBoundsWidth, 500);
        [self.imageView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.height.offset(0);
        }];
        [self layoutIfNeeded];
} completion:^(BOOL finished) {
        [self.imageView stopAnimating];
        [self removeFromSuperview];
        [self.subject sendNext:@1]; //发送信号
}];
    
    
//代码实现
[_showView finishModel:^{
    NSLog(@"close show");
}];

 

posted on 2018-02-05 11:15  东方🐺  阅读(214)  评论(0编辑  收藏  举报

导航