美文网首页swift
21.swift-block循环引用

21.swift-block循环引用

作者: ChaosHeart | 来源:发表于2021-07-23 17:13 被阅读0次

    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("销毁");
        }
    
    }
    
    

    相关文章

      网友评论

        本文标题:21.swift-block循环引用

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