我需要使用线程 class 捕获自我吗?

Do I need capture self using thread class?

我有这个代码:

myThreadTemp = Thread(target: self, selector: #selector(threadMain), object: nil)

 @objc func threadMain(data: AnyObject) {
        let runloop = RunLoop.current
        runloop.add(NSMachPort(), forMode: RunLoopMode.defaultRunLoopMode)
        while !Thread.current.isCancelled{
                //foreground
                DispatchQueue.main.async {[weak self] in

                self?.somemethod()
                self?.somevar = 1
                    print("tick")
                }
            if Thread.current.isCancelled {

            }
            Thread.sleep(forTimeInterval: 1.0)
        }
        runloop.run(mode: RunLoopMode.defaultRunLoopMode, before: NSDate.distantFuture)

    }

或者我可以这样做:

DispatchQueue.main.async {
                self.somemethod()
                self.somevar = 1
                    print("tick")
                }

我看到了这个:

Shall we always use [unowned self] inside closure in Swift

但是是否使用了@objc func

第一个示例看起来无限期地旋转 运行 循环,在滴答之间等待 1 秒,而第二个示例将在下一个 运行 循环迭代中执行一次。在第二种情况下,在捕获 self 方面没有内存管理问题,实际上是因为它只执行一次并且块在它之后被释放(打破了 self 和块之间确实存在的瞬时保留循环)。

假设您尝试每 1 秒打勾一次(正如我根据您的问题猜测的那样),有更好的方法来完成您想要做的事情,using a timer:

// Must be executed on main thread, or other NSRunLoop enabled thread, 
// or the below code will silently do nothing.
self.timer = Timer(timeInterval: 1.0, repeats: true) { [weak self] _ in
    self?.someMethod()
    self?.someVar = 1
    print("tick")
}

// Somewhere in the future, to stop the timer:
// self.timer.invalidate()

正如您在上面的示例中所看到的,对于计时器情况,您可能确实希望使用无主引用或弱引用来引用 self(否则计时器块将对 self 进行强引用,而 self 将对 self 进行强引用)定时器)。该块也应该在使计时器无效时被释放,所以即使在这种情况下,我猜弱引用也不是 100% 必要的。