MaSza
MaSza

Reputation: 465

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?

Upvotes: 0

Views: 70

Answers (2)

danh
danh

Reputation: 62686

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).

Upvotes: 1

Michael S.
Michael S.

Reputation: 91

As long as the view controller you want modified is in the navigation stack, I would try something like this to find the view controller whose properties you want to modify.

 let childVCs = UIApplication.shared.keyWindow!.rootViewController?.childViewControllers
print("childvcs = \(childVCs)")

let myVC = childVCs[0]

let myOtherVC = childVCs[1]

myVC.someProperty = 100

myOtherVC.anotherProperty = 1000

Upvotes: 0

Related Questions