Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone - Call function from another view controller

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.

like image 931
user2779450 Avatar asked Feb 13 '23 11:02

user2779450


1 Answers

Notification Center could be solution to you question.

Receiver UIViewController

- (void)viewDidLoad {
    [[NSNotificationCenter defaultCenter] addObserver:self
        selector:@selector(receiveNotification:) 
        name:@"myNotification"
        object:nil];
}

- (void)receiveNotification:(NSNotification *)notification
{
    if ([[notification name] isEqualToString:@"myNotification"]) {
       //doSomething here.
    }
}

Sender UIViewController

- (void)sendNotification {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"myNotification" object:self];
}
like image 151
modus Avatar answered Feb 16 '23 04:02

modus