16.闭包的使用

2017-05-17  本文已影响27人  xiaoyouPrince

闭包的介绍

闭包的使用

block的用法回顾
@interface HttpTool : NSObject
- (void)loadRequest:(void (^)())callBackBlock;
@end

@implementation HttpTool
- (void)loadRequest:(void (^)())callBackBlock
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSLog(@"加载网络数据:%@", [NSThread currentThread]);

        dispatch_async(dispatch_get_main_queue(), ^{
            callBackBlock();
        });
    });
}
@end
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.httpTool loadRequest:^{
        NSLog(@"主线程中,将数据回调.%@", [NSThread currentThread]);
    }];
}
block的写法:
    类型:
    返回值(^block的名称)(block的参数)

    值:
    ^(参数列表) {
        // 执行的代码
    };
使用闭包代替block
class HttpTools: NSObject {
    func requestData(finishedCallback : @escaping (_ jsonData : String, _ age : Int) -> ()) {
        // 1.创建全局队列, 发送异步请求
        DispatchQueue.global().async {
            print("发送网络请求:\(Thread.current)")

            DispatchQueue.main.async {
                print("回调主线程:\(Thread.current)")

                finishedCallback("123", 30)
            }
        }
    }
}

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        httpTools.requestData { (jsonData :String, age : Int) in
            print("回到控制器,获取到数据")
        }
    }
闭包的写法:
    类型:(形参列表)->(返回值)
    技巧:初学者定义闭包类型,直接写()->().再填充参数和返回值

    值:
    {
        (形参) -> 返回值类型 in
        // 执行代码
    }
    httpTool.loadRequest() {
        print("回到主线程", NSThread.currentThread());
    }
    // 开发中建议该写法
    httpTool.loadRequest {
        print("回到主线程", NSThread.currentThread());
    }

闭包的循环引用

    // 析构函数(相当于OC中dealloc方法)
    deinit {
        print("ViewController----deinit")
    }
class HttpTools: NSObject {

    var finishedCallback : ((_ jsonData : String, _ age : Int) -> ())?

    func requestData(finishedCallback : @escaping (_ jsonData : String, _ age : Int) -> ()) {
        self.finishedCallback = finishedCallback

        // 1.创建全局队列, 发送异步请求
        DispatchQueue.global().async {
            print("发送网络请求:\(Thread.current)")

            DispatchQueue.main.async {
                print("回调主线程:\(Thread.current)")

                finishedCallback("123", 30)
            }
        }
    }
}
    // 解决方案一:
    weak var weakSelf = self
    httpTool.loadData {
        print("加载数据完成,更新界面:", NSThread.currentThread())
        weakSelf!.view.backgroundColor = UIColor.redColor()
    }
    httpTool.loadData {[weak self] () -> () in
        print("加载数据完成,更新界面:", NSThread.currentThread())
        self!.view.backgroundColor = UIColor.redColor()
    }
httpTool.loadData {[unowned self] () -> () in
        print("加载数据完成,更新界面:", NSThread.currentThread())
        self.view.backgroundColor = UIColor.redColor()
    }
上一篇 下一篇

猜你喜欢

热点阅读