Swift 4 / Xcode 9新观察()KVO不安全吗?

时间:2018-03-18 11:54:55

标签: swift swift4 key-value-observing

我有:

// ArticleModel.swift

class ArticleModel
{
    ...
}

// ArticleListViewController.swift

@objcMembers class ArticleListViewModel: NSObject
{
    dynamic var articles: [ArticleModel] = []
}

private var viewModel:        ArticleListViewModel
private var articlesObserver: NSKeyValueObservation?

self.articlesObserver = self.viewModel.observe(\.articles) // Crashes here!
{ [weak self] (viewModel, change) in
    self?.tableView.reloadData()
}

没有编译器警告。然而,当我运行此代码时,它崩溃了:

Thread 1: Fatal error: Could not extract a String from KeyPath Swift.ReferenceWritableKeyPath<App.ArticleListViewModel, Swift.Array<App.ArticleModel>>

这消失了:

// ArticleModel.swift

@objcMembers class ArticleModel: NSObject
{
    ...
}

这是为什么?我知道这个新的KVO表单是完全类型安全的,那么为什么没有编译器警告?

0 个答案:

没有答案