stackOverFlew
stackOverFlew

Reputation: 1489

Calling instance method of one ViewController from another ViewController

I realize this question has been asked to death, at least once a month on stackoverflow for the last couple of years, but I still cannot find a solution.

I have two ViewControllers stemming from a UITabBarController. Both are initialized through the storyboard. I am attempting to call a method of one VC from another. The instance method, of course.

enter image description here

I have heard of the following possibilities:

1: NSNotifications

2: Defining protocol and declaring one VC as the delegate of another.

3: Actually calling the method somehow through RootViewController.

I have the code working through NSNotifications, but I dislike the concept, and I would like to understand the correct way to do it. I am most interested in possibility (3), then (2) as a last resort.

I tried to get (2) to work for several hours, but without initializing the delegate VC from the other VC, I am stumped. (Not an option due to storyboards).

Is either (2) or (3) possible? How so?

What are my misunderstandings about preferred iOS architecture if neither are possible?

Upvotes: 0

Views: 772

Answers (2)

TedCheng
TedCheng

Reputation: 655

I guess using NSNOtification is not always a wrong way to do similar things. I also struggled for this concept.

for this senario, i think notification is okay:

  1. you have a tabbarcontroller containing controller A and B
  2. controller A is a listing of some objects, say, books.
  3. controller B is controller for you to create a book by filling forms and click submit
  4. controller A then update its listing.

the reason is that, the update of Controller A is not due to "clicking of submit". It refresh because a Book is created. It's about something for data. Somehow "A BOOK IS CREATED" is a critical event in an apps.

for another senario, it is not okay

  1. you have a tabbarcontroller containing controller A and B
  2. controller A has a ViewC at the center
  3. controller B has a button, when it's clicked, the ViewC shift up

It's just my own opinion.

Upvotes: 0

tom
tom

Reputation: 19163

Yes, 3 is possible. Let's say you have two UIViewController classes, FooViewController (tab index 0) and BarViewController (tab index 1). And let's say you want to call FooViewController's -(void)doFoo method from BarViewController.

In BarViewController, do [(FooViewController *)[self.tabBarController.viewControllers objectAtIndex:0] doFoo].

Upvotes: 1

Related Questions