请注意,这个问题是在swift之前于2014年7月撰写的 1.0当我大部分时间忽略了关于swift的任何内容并试图"翻译"代码从objC到swift。这不是一个好的解决方案,我现在知道了 更好。 KVO是我们喜欢ObjC的东西,但我强烈建议不要 在swift中使用它并在swift中探索一些替代方案。 http://blog.scottlogic.com/2015/02/11/swift-kvo-alternatives.html。 请记住:如果某些事情很难做到,那么也许并非如此 完成。
作为一个obj-C开发者,我已经习惯了KVO一年,其中一个反复出现的问题是调用removeObserver:forKeyPath:
可能不安全
我通常用@try...@catch
条款包围这个...
现在快速,我还没有找到尝试...抓住东西:)
有关如何解决问题的任何线索?
干杯
这是我的意思的一个例子
override func viewDidLoad()
{
super.viewDidLoad();
self.summaryTextView.text = self.show?.overview;
self.title = self.show?.title;
if(self.show?.imageData)
{
self.posterImageView.image = UIImage(data: self.show?.imageData);
}
else
{
self.posterImageView.image = UIImage(named:"wait");
show?.addObserver(self, forKeyPath: "imageData", options: NSKeyValueObservingOptions.New, context: nil);
}
}
override func viewDidDisappear(animated: Bool)
{
// Will crash if self was not a observer in the first place
self.show?.removeObserver(self, forKeyPath:"imageData");
}
override func observeValueForKeyPath(keyPath: String!, ofObject object: AnyObject!, change: NSDictionary!, context: CMutableVoidPointer)
{
self.posterImageView.image = UIImage(data: self.show?.imageData);
}
答案 0 :(得分:1)
正如另一个回答所说,Swift中还没有尝试捕获。老实说,我会阻止在你提到的场景中使用try / catch。这可以通过跟踪对象的状态轻松解决,这在面向对象编程中总是一件好事。