1.实现:
import UIKit
class AFNetHttp: NSObject {
///1.读取数据
func loadData(callBack : @escaping (_ block : String)->()) {
DispatchQueue.global().async {
print("异步:",Thread.current);
DispatchQueue.main.sync {
print("同步:",Thread.current);
//调用闭包
callBack("callBack");
}
}
}
///2.block作为类型
var callBlock : ((_ call : String)->())?
func getData(call : @escaping (_ block : String)->()) {
self.callBlock = call;
DispatchQueue.global().async {
print("异步:",Thread.current);
DispatchQueue.main.sync {
print("同步:",Thread.current);
//调用闭包
call("call");
}
}
}
}
2.调用:
import UIKit
class BlockViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
///1.手指开始点击
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
///实现方法
///解决循环引用 [weak self]
AFNetHttp.init().loadData {[weak self] (block) in
print("viewController : ",block);
self?.view.backgroundColor = UIColor.red;
}
}
///2.手指开始移动
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
///解决循环引用 [weak self]
AFNetHttp.init().getData {[weak self] (call) in
self?.view.backgroundColor = UIColor.yellow;
}
}
///
deinit {
print("销毁");
}
}
网友评论