Search code examples
iosobjective-cuiviewcontrollerdelegation

Communication between two not directly connected ViewControllers


I'd like to let ViewController F communciate with ViewController C. They are arranged like this: Navigation Controller A embeds ViewController B, which presents ViewController C inside of a container view. There's a segue from ViewController B to NavigationController D, that embeds ViewController E and ViewController F (segue between E and F).

My current working solution is the following: Build up a delegation "path" between the necessary ViewControllers: ViewController F delegates to ViewController E, which delegates to ViewController B, that finally delegates the information to ViewController C.
It feels like there must be an easier way to do this. Can you recommend one? Maybe hand over ViewController C inside of the "segue path" to ViewController F to set up a direct delegation between C and F?

Thanks!


Solution

  • I would use NSNotification

    In ViewController F:

    - (void)sendData {
        // Fire the notification
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ReceivedData" 
                                                            object:nil];   
    }
    

    In ViewController C:

    - (void)viewDidLoad {
        [NSNotificationCenter defaultCenter] addObserver:self 
                                                selector:@selector(receivedDataNotification:) 
                                                    name:@"ReceivedData" 
                                                  object:nil];
    }
    
    - (void)receivedDataNotification:(id)object {
        NSLog(@"Received Data!");
    }