iPhone - 从另一个视图控制器调用函数

时间:2014-07-17 23:39:25

标签: ios objective-c uiviewcontroller

我有一个名为sendDataToMotor的函数。它在我的First View Controller类中。我有另一个名为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具有未知的名称类型。

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

3 个答案:

答案 0 :(得分:6)

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

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

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

答案 1 :(得分:1)

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

第二行中的这一行:

 @property(nonatomic,assign)UIViewController* firstController;

应该概括为不参考特定类型

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

你应该在你的secondVC的标题中(在@interface声明之上)附带协议声明,类似

@protocol SecondVCDelegate
   - (void) sendDataToMotor;
@end

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

  @interface firstVC < SecondVCDelegate >

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

  @interface firstVC() < SecondVCDelegate >

然后您将不需要使用performSelector(无论如何应该先进行安全检查),因为编译器会提醒您错误。

在创建secondVC之后的firstVC中,将它的委托属性设置为self(即firstVC)

 secondVC.delegate = self;

然后在secondVC中你可以直接在它的委托上调用方法:

[self.delegate sendDataToMotor];

我在这里以更多(罗嗦)细节解释这个......

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

答案 2 :(得分:0)

您的代码中存在许多问题。我将假设您包含的第二块代码实际上位于-viewDidLoad中的FirstViewController而不是第二块。

  1. 您获得的错误是因为您没有在secondViewController之前输入类型。它应该是SecondViewController *secondViewController = ...
  2. 这可能仍然不适合您,因为当您执行到第二个视图控制器的转换时,您将不会使用相同的对象。
相关问题