美文网首页
闭包基本使用

闭包基本使用

作者: ZLWorm | 来源:发表于2015-12-27 00:07 被阅读0次

    GCD异步

    • 模拟在子线程加载数据
    func loadData() {
        dispatch_async(dispatch_get_global_queue(0, 0), { () -> Void in
            print("耗时操作 \(NSThread .currentThread())")
        })
    }
    
    • 尾随闭包: 如果闭包是参数里面最后一个参数,那么参数的括号可以提前关闭,闭包可以写在外面
    func loadData() {
        dispatch_async(dispatch_get_global_queue(0, 0)) { () -> Void in
            print("耗时操作 \(NSThread .currentThread())")
        }
    }
    
    • 闭包的简写: 如果闭包中没有参数和返回值,可以省略
    func loadData() {
        dispatch_async(dispatch_get_global_queue(0, 0)) {
            print("耗时操作 \(NSThread .currentThread())")
        }
    }
    

    自定义闭包参数,实现主线程回调

    override func viewDidLoad() {
            super.viewDidLoad()
            
            // 网络请求完成之后执行的闭包
            let clourse = { (response: String) -> () in
                print("数据请求完毕:\(response)")
                print("更新ui")
            }
            
            // 加载数据,传入数据加载完成要执行闭包
            loadData(clourse)
            
            
        }
    // 这个方法是专门用来加载数据的
        func loadData(callback: (response: String) -> ()){
            
            // 模拟异常加载数据
            dispatch_async(dispatch_get_global_queue(0, 0)) {
                // 执行耗时操作
                NSThread.sleepForTimeInterval(2)
                // 模拟请求回来的数据
                let response = "办证 138xxxxx"
                
                dispatch_async(dispatch_get_main_queue(), {
                    // 在主线程里面执行的代码,比如 更新 UI
                    
                    // 把请求回来的数据通过闭包的方式把数据回调到外面
                    print(response)
                    callback(response: response)
                })
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:闭包基本使用

          本文链接:https://www.haomeiwen.com/subject/pxjbhttx.html