2016-10-25 52 views
0

我有这样的代码:我是否需要使用线程类捕获自己?

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

第一个示例将无限期地旋转runloop,在tick之间等待1s,而第二个示例将在下一次运行循环迭代中执行一次。在第二种情况下,在捕获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() 

正如你在上面的例子中可以看出,对于定时器的情况,你可能确实想要用无主的或弱的引用来引用自己(因为定时器模块会强烈地引用自身,而对自定义则是强烈的引用)。该块应该在使计时器无效时释放,所以即使在这种情况下,我猜也并非100%必需的弱引用。

相关问题