Calling a function from another class - Obj C

I am trying to figure out how I can call a function from another one of my classes. I use RootViewController to set one of my views, as you can say, AnotherViewController

So in my AnotherViewController I'm going to add to the .h file

@class RootViewController 

And in the .m file that will be imported View

 #import "RootViewController.h" 

I have a function called:

 -(void)toggleView { //do something } 

And then in my AnotherViewController I have a button assigned as:

  -(void)buttonAction { //} 

In buttonAction, I would like to be able to call the toggleView function in my RootViewController.

Can someone clarify how I do this.

I tried to add this to my button:

 RootViewController * returnRootObject = [[RootViewController alloc] init]; [returnRootObject toggleView]; 

But I do not think this is right.

Thanks for the advanced.

+4
source share
2 answers

You need to create a delegate variable in your AnotherViewController, and when you initialize it from the RootViewController, set the instance of RootViewController as the delegate of AnotherViewController.

To do this, add the instance variable to AnotherViewController: "id delegate;". Then add two methods to AnotherViewController:

 - (id)delegate { return delegate; } - (void)setDelegate:(id)newDelegate { delegate = newDelegate; } 

Finally, in the RootViewController, where AnotherViewController is initialized, do

 [anotherViewControllerInstance setDelegate:self]; 

Then when you want to execute toggleView do

 [delegate toggleView]; 

Alternatively, you can make your RootViewController a single, but the delegation method is definitely better. I also want to note that the method I was telling you about was Objective-C 1.0. Objective-C 2.0 has some new features, however, when I studied Obj-C, it was very confusing for me. I would like to get 1.0 down before looking at the properties (this way you will understand what they do in the first place, they basically just automatically create getters and setters).

+1
source

I tried NSNotificationCentre - it works like a charm - Thanks for your answer. I couldn't get it to work, but NS came across it.

 [[NSNotificationCenter defaultCenter] postNotificationName:@"switchView" object: nil]; 
+1
source

Source: https://habr.com/ru/post/1313134/


All Articles