I have a function called sendDataToMotor. It is in my First View Controller classes. I have another view controller called SecondViewController. I need to call this function from the Second View Controller.m class. I tried declaring the property:
@property(nonatomic,assign)UIViewController* firstController;
in my SecondViewController.h class. Furthermore, I wrote the code bellow in the viewDidLoad part of my SecondViewController.m class (where I want the function to be called).
secondViewController = [[SecondViewController alloc] initWithNibName:@"secondViewController" bundle:nil];
secondViewController.firstController = self;
[self.firstController performSelector:@selector(sendDataToMotor)];
But, Im getting an error with the first word in that code (secondViewController) because of an undeclared identifier issue. Furthermore, I get an error with the second line (secondViewController.firstController = self) because secondViewController has an unknown name type.
In summary, I don't care if you use the above code to answer my question: that was just something I tried to implement that I found online. However, I'm looking for the simplest way to call a function from another View Controller.
There are many problems in your code. I'm going to assume the second chunk of code you included is actually in
-viewDidLoad
inFirstViewController
not the second.secondViewController
. It should beSecondViewController *secondViewController = ...
You want to use the delegate pattern, and you are almost there.
This line in secondVC:
should be generalised so as not refer to a specific type
And you should accompany that with a protocol declaration in the header of your secondVC (above the @interface declaration), something like
In firstVC interface you can declare your adherence to the delegate protocol in the first line of the @interface declaration in the header file
Or in the first line of a private interface declaration in the .m file
Then you won't need to use
performSelector
(which anyway should be preceded by a safety check) as the compiler will alert you of errors.In firstVC after creating secondVC, set it's delegate property to self(i.e. firstVC)
then in secondVC you can just call the method directly on it's delegate:
I explain this in more (wordy) detail here...
https://stackoverflow.com/a/14910469/1375695
Notification Center could be solution to you question.
Receiver UIViewController
Sender UIViewController