【问题标题】:Do I need capture self using thread class?我需要使用线程类捕获自我吗?
【发布时间】:2016-10-25 14:35:58
【问题描述】:

我有这个代码:

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被使用了吗?

【问题讨论】:

    标签: swift grand-central-dispatch weak-references


    【解决方案1】:

    第一个示例看起来无限期地旋转运行循环,在滴答之间等待 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 对计时器进行强引用)。该块也应该在使计时器无效时被释放,所以即使在这种情况下,我猜也不是 100% 需要弱引用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-14
      • 1970-01-01
      • 1970-01-01
      • 2020-07-29
      • 1970-01-01
      • 1970-01-01
      • 2021-11-14
      相关资源
      最近更新 更多