Swift中的KVO /异常处理

Flo*_*rel 6 ios swift

请注意,这个问题写于2014年7月,在swift 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);

}
Run Code Online (Sandbox Code Playgroud)

xtr*_*var 1

正如另一个答案所说,Swift 中还没有 try-catch。老实说,我不鼓励在您提到的场景中使用 try/catch。通过跟踪对象的状态可以轻松解决这个问题,这在面向对象编程中始终是一件好事。