(Swift基础)day01_(15)Swift中的闭包_201

2018-08-22  本文已影响0人  lyh165

文丨lyh165
发布时间:2018-08-22 (周三 广州/雨)
最后更新时间:2018-08-22 (周三 广州/雨)

官方文档
1、Welcome to Swift.org(欢迎来到Swift.org)
2、Using the Package Manager(使用包管理器)
3、A Swift Tour(快速之旅)
官方swift快速之旅code


闭包

闭包的介绍

闭包的使用

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 HttpTool: NSObject {

    func loadRequest(callBack : ()->()){
        dispatch_async(dispatch_get_global_queue(0, 0)) { () -> Void in
            print("加载数据", [NSThread.currentThread()])

             dispatch_async(dispatch_get_main_queue(), { () -> Void in
                callBack()
             })
        }
    }
}

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        // 网络请求
        httpTool.loadRequest ({ () -> () in
            print("回到主线程", NSThread.currentThread());
        })
    }

闭包的写法:
    类型:(形参列表)->(返回值)
    技巧:初学者定义闭包类型,直接写()->().再填充参数和返回值

    值:
    {
        (形参) -> 返回值类型 in
        // 执行代码
    }

闭包的简写
    httpTool.loadRequest({
        print("回到主线程", NSThread.currentThread());
    })

    httpTool.loadRequest() {
        print("回到主线程", NSThread.currentThread());
    }

    // 开发中建议该写法
    httpTool.loadRequest {
        print("回到主线程", NSThread.currentThread());
    }

闭包的循环引用

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

class HttpTool: NSObject {

    // 定义属性,来强引用传入的闭包
    var callBack : (()->())?

    func loadRequest(callBack : ()->()){
        dispatch_async(dispatch_get_global_queue(0, 0)) { () -> Void in
            print("加载数据", [NSThread.currentThread()])

             dispatch_async(dispatch_get_main_queue(), { () -> Void in
                callBack()
             })
        }

        self.callBack = callBack
    }
}

    // 解决方案一:
    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()
    }

上一篇 下一篇

猜你喜欢

热点阅读