【问题标题】:Calling method from other controller从其他控制器调用方法
【发布时间】:2014-02-18 21:52:39
【问题描述】:

我知道有人在 SO 上问过其他类似的问题,但我已经通过了他们和他们的建议,但根本无法解决这个问题。

我有一个带有关联 h 和 m 文件的视图控制器,它们访问另一个 h 和 m 文件(不是视图控制器)。

这个其他被调用的文件在完成后需要在其父级上调用一个函数,但我无法让它在父级中调用一个函数。

代码sn-ps:

ParentViewController.h:

#import <UIKit/UIKit.h>

@interface ParentViewController : UIViewController <UITextFieldDelegate> {
....
}

@end

ParentViewController.m:

#import "ParentViewController.h"
#import "OtherView.h"

@implementation ParentViewController

- (void)callThis {
    NSLog(@"this is not called");
}

@end

OtherView.h:

#import <UIKit/UIKit.h>

@interface OtherView : UIView {
...
}

@end

OtherView.m:

#import "OtherView.h"

@implementation OtherView

-(void)done {
    [self callThisFirst];
    [ParentViewController callThis];
}

-(void)callThisFirst {
    NSLog(@"This is called");
}

@end

谁能帮我在父文件中调用该方法?

谢谢

【问题讨论】:

  • 首先您需要将ParentViewController 实例传递给OtherView 实例。你在哪里初始化你的 OtherView 对象?我们能看到那个代码吗?
  • 可能很明显,但请确保 -(void)callThis; 在您的 ParentViewController 的 .h 中
  • 但可以肯定的是,如果用户收到编译器错误消息,就像他会告诉我们的那样。 ;)

标签: ios function call


【解决方案1】:

首先,您创建的方法是一个实例方法,因为它以- 为前缀,但是在您尝试调用它的地方,看起来您正在尝试调用类方法,因为您是不指定对象,你指定类名。

其次,在您的 ParentViewController 类中,您没有显示在头文件中声明的方法 callThis,这意味着 OtherView 对该方法一无所知。您必须将以下行添加到 ParentViewController.h 中的 @interface

- (void)callThis;

第三,您必须将 #import for ParentViewController.h 添加到您的 OtherView 类的 OtherView.m 以了解 ParentViewController 类。

【讨论】:

    【解决方案2】:

    所以在你的 ParentViewController.h 你有:

    ...}
    
    @end
    

    也就是说,您没有声明要调用的方法。但是我们可以看到它是一个实例方法,因为实现说:

    - (void)callThis { //...
    

    但你试图把它当作类方法来调用:

    [ParentViewController callThis];
    

    那是行不通的。 ParentViewController 没有 +callThis 方法,所以没有骰子。您需要将ParentViewController 的实例传递给另一个对象,然后像这样调用它:

    [theParentViewController callThis];
    

    其中theParentViewController 是指向实际ParentViewController 对象的指针。您还需要将 -callThis 的声明添加到 ParentViewController.h,即:

    ...}
    
    -(void)callThis;
    
    @end
    

    【讨论】:

      【解决方案3】:

      看起来您希望 ParentViewController 上的 callThis 成为类方法而不是实例方法。

      只需将:-(void)callThis 更改为 +(void)callThis 并将该签名复制到 ParentViewController.h 中的 @interface 声明中。

      您还需要在 OtherView.m 中调用 #import "ParentViewController.h"。您不需要在 ParentViewController.h 中使用 #import "OtherView.h",因为您没有引用该类中的任何内容。

      【讨论】:

      • 如果您真的打算将callThis 用作类方法,这是一个很好的解决方案。只要确保您了解类方法和实例方法之间的区别——它们是完全不同的。 更新:我注意到OP在实现中将callThis改为实例方法,所以这里的解决方案不再适用。
      猜你喜欢
      • 2013-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-13
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 2018-03-25
      相关资源
      最近更新 更多