Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Communication between Model and ViewController

I am developing an app based on the Master-View template provided by Apple (it consists of two ViewControllers, the MasterViewController and the DetailViewController). I have added a Model for communication with my server.

However, when my Model receives a message from the server, it needs to call a method in the MasterViewController or DetailViewController class. How can I do this?

All help is greatly appreciated.

like image 828
danielmhanover Avatar asked Mar 15 '26 16:03

danielmhanover


2 Answers

You could fire notifications from the model, which are handled by the Master and Detail View controllers.

In the model:

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

Handle the "ReceivedData" notification in your View Controller(s):

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

- (void)receivedDataNotification:(id)object {
    NSLog(@"Received Data!");
}
like image 112
melsam Avatar answered Mar 17 '26 05:03

melsam


Actually the MVC pattern that Apple proposes allows for notifications from the model to the controller.

A good way to achieve this goal could be to deliver NSNotification objects through the NSNotificationCenter when your data changes, with information on what is changed, and let the listeners take care of it.

like image 30
diegoreymendez Avatar answered Mar 17 '26 04:03

diegoreymendez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!