【问题标题】:iPhone - Call function from another view controlleriPhone - 从另一个视图控制器调用函数
【发布时间】:2014-07-17 23:39:24
【问题描述】:

我有一个名为 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 的名称类型未知。

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

【问题讨论】:

    标签: ios objective-c uiviewcontroller


    【解决方案1】:

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

    接收者 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];
    }
    

    【讨论】:

      【解决方案2】:

      您想使用委托模式,而且您快到了。

      secondVC 中的这一行:

       @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(无论如何都应该在安全检查之前),因为编译器会提醒你错误。

      在firstVC中创建secondVC后,将其delegate属性设置为self(即firstVC)

       secondVC.delegate = self;
      

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

      [self.delegate sendDataToMotor];
      

      我在这里更详细地解释这个(罗嗦)......

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

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

          猜你喜欢
          • 2017-03-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多