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
)
Apple表示:「只要有效的引用在其生命週期的某個時刻變爲零,就使用弱引用;相反,如果知道在初始化過程中引用永遠不會爲零,那麼使用無主引用「。 – larva
也許你的答案在這裏http://stackoverflow.com/questions/24468336/how-to-correctly-handle-weak-self-in-swift-blocks-with-arguments – larva