闭包基本使用

2015-12-27  本文已影响0人  ZLWorm

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)
            })
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读