ios Blocks

一、block简介

直接上一张大神的图,block组成一下子就看明白了


ios Blocks_第1张图片
图片.png

PS:其他的就不多做介绍了,文章末尾有收集的链接,很全面

二、

Block回调
(通俗讲就是在一个方法中声明block,并在此方法中合适的地方使用它,当这个方法在其他地方被调用时,需要实现block的本体,执行过程:方法被调用-->执行方法-->执行到使用block的地方-->程序会执行他的本体,而本体在调用此方法的地方,因此程序回调到调用处,执行block本体)
其实就犹如一个方法声明和使用在一处,而实现确在另一处,使用时就自然而然的执行实现的代码
PS:整个执行过程是同步的,只是来回调用

  • 声明block类型的变量,并在合适的地方调用
- (void )httpRequestWithStringUrl:(NSString *)strUrl complet:(void (^)(NSDictionary *responseDic, BOOL isSeccuss))complete{
    
    strUrl = [strUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    NSURL *url = [NSURL URLWithString:strUrl];
    
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
    NSURLSession *session = [NSURLSession sharedSession];
    
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *taskError){
        NSLog(@"Register请求完成!");
        if (!taskError) {
            //NSError *jsonError = nil;
          NSDictionary *responseDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            complete(responseDic,YES);
        }else{
            NSLog(@"\ntask error: %@", taskError.localizedDescription);
            complete(nil,NO);
        }
    }];
    
    [task resume];
}

  • 在使用含有block的方法时,书写block本体,当block变量在被调用的方法中使用是,程序就会回调,执行block的本体
[[WebConnect sharedWebConnect] httpRequestWithStringUrl:strUrl complet:^(NSDictionary *responseDic, BOOL isSeccuss){
        if (isSeccuss) {
            NSLog(@"netObject: %@",responseDic);
        }
    }];


参考:
注重使用
Objective-C语法之代码块(block)的使用
block专题
block专栏
原理基础
Objective-C中的Block

你可能感兴趣的:(ios Blocks)