0

请参阅下面的编辑以了解当前(次要)问题


我试图在 MainViewController.m 和 FlipsideViewController.m 之间调用方法(方法对,而不是函数?)——从一个文件/类到另一个。

我想这就是通常所说的“从另一个类调用方法”。我知道,周围有很多这样的问题,但我就是无法让它正常工作。

就我而言,我在上述两个文件中都有几个用户定义的方法/函数。有时,我需要从位于 MainViewController.m 文件中的 FlipsideViewController.m 中调用一个方法

// in MainViewController.m

- (void) calculateDays {
    //executes caluculations
   // inserts data into labels, etc 
}

如果我想简单地从同一个文件中调用此函数,我只需:

[self calculateDays];

这很简单,但是,我也想从 FlipsideViewController.m 文件中调用此函数,反之亦然。那么我该怎么做呢?这个这个这个问题有点回答它,但它对我来说并不完全有效。我会在一秒钟内解释为什么。

这是我尝试过并认为应该有效的方法:

MainViewController *mvs = [[MainViewController alloc] init]; //alloc init MVC
[mvs calculateDays]; //call "external" function

它给了我错误:"Unknown type name MainViewController"。所以我假设我必须以某种方式包含/导入它才能使其工作(就像在 javascript 或 PHP 中一样)。所以我将它包含在 FlipSideViewController.m 类中:

 #import "MainViewController.h"

到目前为止没有错误。然后我尝试编译/构建它并遇到另一个错误: “clang:错误:链接器命令失败,退出代码 1(使用 -v 查看调用)”“ld:架构 armv7s 的 3 个重复符号”

使我认为像这样导入 MainViewController 不是可行的方法,因为然后我会导入许多其他可能会干扰 FlipSideViewController 类中的某些代码的东西。

尝试过类似的解决方案,但似乎没有任何效果。谁能向我解释我做错了什么,也许如何正确地做到这一点:在 MainViewController.m 和 FlipsideViewController.m 之间调用方法,反之亦然。


H2CO3 提出的解决方案确实解决了大部分问题(XCode 出现了一段时间的错误并给了我随机错误,迫使我重新构建整个项目),但仍有一件事不太奏效:更改 UILabel 的内容(UIOutlet)。请看看你们中是否有人可以帮助我:

当从self内部调用该方法时(即[self calculateDay]),该值被成功插入到UILabel中。从FlipsideViewController调用时,插入的值存在并处理成功,但无法插入 UILabel。请看下文。

一些日志记录:

//method called from within self on viewDidLoad: [self calculateDay];
Processed value to update label with: 26
New value in outlet after having been inserted: 26


//method called from another (FlipsideViewController) class file: [mvs calculateDay];
Processed value to update label with: 26
New value in outlet after having been inserted: (null)

/* 
  This doesn't work either from that external file: 
  [[mvs LabelName] setText:@"Hello, update label!"]; no errors but no display either

*/
4

2 回答 2

2

如果您改为导入标头,则应该为您提供所有必要的声明,但您不会出现“重复符号”链接器错误。这是编写(Objective-)C 代码的“标准”/常见做法。

#import "MainViewController.h"
                            ^
      ".h" instead of ".m" -+
于 2013-01-05T17:07:48.240 回答
0

(外行的术语)在 Objective-C 中,您只能使用每个文件都知道的对象。在此示例中,您尝试在 FlipsideController.m 文件中使用 MainViewController。FlipsideController.m 不知道 MainViewController 是什么,因此它会抛出错误,因为它不知道它是什么或如何使用它。您有两个选项可以告诉 Flipsidecontroller MainViewController 是什么,您可以导入标头 ( #import "MainViewController.h"),这将使您可以完全访问 FlipSideController.h 中定义的所有内容。(除非您真的知道自己在做什么,否则您可能永远不应该导入 .m)您还可以创建前向声明 -@class FilpsideController在 .h 中并在 .m 中导入文件。这对于避免循环导入等很有用。

于 2013-01-05T17:12:59.737 回答