iPhone-从另一个视图控制器调用功能 [英] iPhone - Call function from another view controller

查看:95
本文介绍了iPhone-从另一个视图控制器调用功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为sendDataToMotor的函数.它在我的First View Controller类中.我有另一个名为SecondViewController的视图控制器.我需要从Second View Controller.m类中调用此函数.我尝试声明该属性:

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;

在我的SecondViewController.h类中.此外,我在SecondViewController.m类的viewDidLoad部分中编写了下面的代码(我希望在其中调用该函数).

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)];

但是,由于未声明的标识符问题,我在该代码中的第一个单词(secondViewController)出现错误.此外,由于secondViewController具有未知的名称类型,因此第二行出现了错误(secondViewController.firstController = self).

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.

总而言之,我不在乎您是否使用上面的代码来回答我的问题:那只是我尝试实现的在线发现的东西.但是,我正在寻找从另一个View Controller调用函数的最简单方法.

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.

推荐答案

通知中心可以解决您的问题.

Notification Center could be solution to you question.

接收器UIViewController

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

发件人UIViewController

Sender UIViewController

- (void)sendNotification {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"myNotification" object:self];
}

这篇关于iPhone-从另一个视图控制器调用功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆