Swift PerformSelector

一、Runloop


无输入的sources 或 timers事件源,那么runloop会立即退出。
image.png

一、PerformSelector延迟事件


perform(<#T##aSelector: Selector##Selector#>, with: <#T##Any?#>, afterDelay: <#T##TimeInterval#>)
作用向当前Runloop添加一个timer事件源

1.1、在子线程执行未开启runloop

override func touchesBegan(_ touches: Set, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        print("touchesBegan1")
        DispatchQueue.global().asyncAfter(deadline: .now() + 3) { [self] in
            print("touchesBegan2")
            self.perform(#selector(onPerformAction), with: nil, afterDelay: 1)
            print("touchesBegan3")
        }
        print("touchesBegan4")
    }
    
    @objc func onPerformAction() {
        print("onPerformAction:\(Thread.current)");
    }
image.png
1.2、在子线程执行开启runloop 结果: 执行onPerformAction成功

override func touchesBegan(_ touches: Set, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        print("touchesBegan1")
        DispatchQueue.global().asyncAfter(deadline: .now() + 3) { [self] in
            print("touchesBegan2")
            // 下面这行代码等于向当前runloop添加timer事件源
            self.perform(#selector(onPerformAction), with: nil, afterDelay: 1)
           // 开启runloop时,已经有timer事件源,所以runloop不会因为无任何事件源而退出
            RunLoop.current.run()
            print("touchesBegan3")
        }
        print("touchesBegan4")
    }
image.png

image.png
1.3、在子线程执行开启runloop 结果:执行onPerformAction失败

override func touchesBegan(_ touches: Set, with event: UIEvent?) {
       super.touchesBegan(touches, with: event)
       print("touchesBegan1")
       DispatchQueue.global().asyncAfter(deadline: .now() + 3) { [self] in
           print("touchesBegan2")
           RunLoop.current.run()
           self.perform(#selector(onPerformAction), with: nil, afterDelay: 1)
           print("touchesBegan3")
       }
       print("touchesBegan4")
   }
image.png
image.png
1.4、取消PerformSelector延迟事件

@objc func onCancelPerformAction() {
        /** 1.单独取消perform的执行事件*/
        NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(onPerformAction), object: nil)
        /** 2.取消perform的所有执行事件*/
        NSObject.cancelPreviousPerformRequests(withTarget: self)
    }

你可能感兴趣的:(Swift PerformSelector)