lapserdak lapserdak - 9 months ago 59
Objective-C Question

Constantly passing data between two view controllers iOS

I'm new in objective-c. I try to send data between 2 view controllers (for example controllerA and controllerB), but I need this data constantly, so I use _displaylink in controllerB to call method from controllerA. I use player in controllerA and I want to display time etc. in controllerB. How to get existing instance of controllerA?

I try 2 different ways to do this, but both create new instance of viewcontroller

example 1:

RootViewController *controller=(RootViewController *)self.presentedViewController;

example 2:

RootViewController *parent=self.parentViewController;

When I use this solutions I can call the method from controllerA (but this is method from new instance :( )

I also try this solution:

RootViewController *rootController =(RootViewController*)[[(AppDelegate*)
[[UIApplication sharedApplication]delegate] window] rootViewController];

But when I try call the method in I get this error:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[MMDrawerController
playerPositionS]: unrecognized selector sent to instance 0x7c406c00'

Any ideas how to call this method correctly?

Answer Source

In MVC as implemented in iOS/Objective-C, view controllers refer to a shared model, not to to each other. They should observe changes in that model, and then update their UIs accordingly.

A few ways to observe changes:

  • KVO - connects changes to model values to a target and selector in the observer
  • Notification - allows the model to "post" that it's changed and view controllers to "observe" those posts.
  • Delegation - this is the most direct (most overused, IMO) approach, where one object provides completes the function for another over some well-defined interface (a protocol).