2016-09-16 27 views
2

在斯威夫特爲境界文檔境界通知,對notifications部分有此示例代碼:,捕捉[弱自我]斯威夫特

class ViewController: UITableViewController { 
    var notificationToken: NotificationToken? = nil 

    override func viewDidLoad() { 
    super.viewDidLoad() 
    let realm = try! Realm() 
    let results = realm.objects(Person.self).filter("age > 5") 

    // Observe Results Notifications 
    notificationToken = results.addNotificationBlock { [weak self] (changes: RealmCollectionChange) in 
     guard let tableView = self?.tableView else { return } 
     // ... some code removed here ... 
    } 
    } 

    deinit { 
    notificationToken?.stop() 
    } 
} 

我想知道爲什麼[weak self]這裏用來代替[unowned self]。在什麼情況下self可以在這裏? (前到達deinit

+0

Apple表示:「只要有效的引用在其生命週期的某個時刻變爲零,就使用弱引用;相反,如果知道在初始化過程中引用永遠不會爲零,那麼使用無主引用「。 – larva

+0

也許你的答案在這裏http://stackoverflow.com/questions/24468336/how-to-correctly-handle-weak-self-in-swift-blocks-with-arguments – larva

回答

2

在這種特定情況下它不能是有史以來nil因爲通知塊將永遠不會stop()後調用被調用,unowned就可以了。使用weak只是爲了使其更強大,在有人將代碼複製並粘貼到看起來相似的情況下,但實際上並不保證self永遠不會是nil