2016-10-25 51 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%必需的弱引用。

相關問題