gpt4 book ai didi

ios - Swift 中的 KVO/异常处理

转载 作者:搜寻专家 更新时间:2023-10-30 22:18:10 24 4
gpt4 key购买 nike

Please note that this question was written in july 2014, before swift 1.0 when I mostly ignored anything about swift and tried to "translate" code from objC to swift. This is not a good solution and I now know better. KVO is something we love in ObjC, but I strongly recommend not to use it in swift and explore some alternative in swift. http://blog.scottlogic.com/2015/02/11/swift-kvo-alternatives.html. Remember: if something is hard to do, then maybe it is not meant to be done.

作为一名 obj-C 开发人员,我已经习惯 KVO 好一年了,其中一个反复出现的问题是调用 removeObserver:forKeyPath: 的潜在不安全性我通常用 @try...@catch 子句包围它...现在有了 swift,我还没有找到 try ... catch thingy :)关于如何解决该问题的任何线索?

干杯

下面是我的意思的例子

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);

}

最佳答案

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

关于ios - Swift 中的 KVO/异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24077179/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com