tags:

views:

1262

answers:

1
+7  A: 

Key-value observing notifications occur on the same thread in which the observed property was changed on. Apple mentions the following warning in the NSOperation class reference:

"Although you can attach observers to these properties, you should not use Cocoa bindings to bind them to elements of your application’s user interface. Code associated with your user interface typically must execute only in your application’s main thread. Because an operation may execute in any thread, any KVO notifications associated with that operation may similarly occur in any thread."

In your observeValueForKeyPath:ofObject:change:context: method, you should perform any UIKit operations on the main thread. Since you're performing multiple steps in there, you might actually want to create another method in your observing class called -dataLoadingFinished which you can call on the main thread from inside observe:…. You can then include all of your UI calls in there, rather than having to call performSelectorOnMainThread for each one:

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
  [self performSelectorOnMainThread:@selector(dataLoadingFinished:) withObject:nil waitUntilDone:YES];
}

Even in cases where threading is not an issue, it is customary to define separate methods to actually implement each observation action, to prevent the observe:… from growing too large.

Also note that even though you are only observing one property, it is still better practice to validate that the property you are interested in is the one prompting the change notification. See Dave Dribin's article Proper KVO Usage for the best way in which to do this.

Sean Murphy