0

I'm trying to use Storyboards and to reduce coupling between my classes using KVC. Like the Contacts app, I have editable fields that push new view controllers where you can edit data. Before I show one of my detailViewControllers, I do things like this

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([[segue identifier] isEqualToString:@"ShowDetailMap"]) {
        UIViewController *destination = ((UINavigationController *)segue.destinationViewController).topViewController;

        if ([destination respondsToSelector:@selector(setMapTypeAsNum:)]) {
            [destination setValue:[NSNumber numberWithInteger:self.mapView.mapType] forKey:@"mapTypeAsNum"];

            [destination addObserver:self forKeyPath:@"mapTypeAsNum" options:NSKeyValueObservingOptionNew context:NULL];
        }

How do you removeObserver and maintain loose coupling between classes? I can conform my viewController class to the UINavigationControllerDelegate protocol, but it seems bad to do something like:

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {

    if ([viewController respondsToSelector:@selector(setNewmap:)]) {
        if ([[navigationController topViewController] isKindOfClass:[AddMapViewController class]]) {
           // remove observer
        }
    }
}

It seems like there should be a better way to removeObserver than checking if the DetailViewController is of a certain type and remove that observer for that view controller. What would you reocommend? Thanks.

Crystal
  • 28,460
  • 62
  • 219
  • 393

1 Answers1

0

One way to do it is to make all your base classes has two methods

  • one for registering the observer that takes the target and observation key as parameters. the function in the base class would do nothing, this function will be inherited and redefined in child classes to register the observer
  • the other function will remove the observation to that key or to all observation keys. this function will do nothing in the base class, but on the derived classes it will remove the observation keys that you specify if they conforms to

using this method the decoupling of views will be maximized since none of the callers will have to worry if the classes conforms or not to the given observation

Omar Abdelhafith
  • 21,163
  • 5
  • 52
  • 56