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.
As an obj-C dev, I've been used to KVO for, well, year, and one of the recurring problem is the potential unsafe of calling removeObserver:forKeyPath:
I usually surround this with a @try...@catch
clause...
Now with swift, I haven't find yet the try ... catch thingy :)
Any leads on how to workaround the problem?
Cheers
Here is a example of what i mean
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);
}