iPhone – 从另一个视图控制器调用function

我有一个叫做sendDataToMotor的函数。 这是在我的第一个视图控制器类。 我有另一个视图控制器称为SecondViewController。 我需要从Second View Controller.m类调用这个函数。 我试过声明属性:

@property(nonatomic,assign)UIViewController* firstController; 

在我的SecondViewController.h类中。 此外,我在我的SecondViewController.m类的viewDidLoad部分(我希望函数被调用的地方)写下了代码。

 secondViewController = [[SecondViewController alloc] initWithNibName:@"secondViewController" bundle:nil]; secondViewController.firstController = self; [self.firstController performSelector:@selector(sendDataToMotor)]; 

但是,由于未声明的标识符问题,我得到该代码(secondViewController)中的第一个单词的错误。 此外,我得到第二行(secondViewController.firstController = self)的错误,因为secondViewController有一个未知的名称types。

总之,我不在乎你是否使用上面的代码来回答我的问题:那只是我试图实现的,我在网上find的。 不过,我正在寻找从另一个View Controller调用函数的最简单的方法。

通知中心可以解决你的问题。

接收器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

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

你想使用委托模式,你几乎在那里。

第二个VC中的这一行:

  @property(nonatomic,assign)UIViewController* firstController; 

应该是泛化的,以便不涉及具体的types

  @property(nonatomic,weak)id <delegateProtocol> delegate; 

你应该在你的第二个VC的头文件(在@interface声明的上面)附带一个协议声明,就像

 @protocol SecondVCDelegate - (void) sendDataToMotor; @end 

在firstVC接口中,您可以在头文件的@interface声明的第一行中声明您遵守委托协议

  @interface firstVC < SecondVCDelegate > 

或者在.m文件中的私有接口声明的第一行

  @interface firstVC() < SecondVCDelegate > 

那么你不需要使用performSelector (反正应该在安全检查之前),因为编译器会提醒你错误。

在创build第二个VC后的firstVC中,将它的delegate属性设置为self(即firstVC)

  secondVC.delegate = self; 

那么在第二个VC你可以直接调用它的委托方法:

 [self.delegate sendDataToMotor]; 

我在这里解释更多(罗嗦)细节…

https://stackoverflow.com/a/14910469/1375695

你的代码有很多问题。 我将假设你包含的第二个代码段实际上是在-viewDidLoad中的FirstViewController而不是第二个。

  1. 你得到的错误是因为你没有把这个types放在secondViewController之前。 它应该是SecondViewController *secondViewController = ...
  2. 这可能仍然不会为你工作,因为当你执行到第二个视图控制器的转换,你将不会使用相同的对象。