了解 Swift 个文件之间的交互 ​​- 我如何从一个文件调用另一个文件

Understanding interaction between Swift files - how do I call from one to the other

我有我的 ViewController.swift,这是应用程序加载时第一个 运行。然后我转到另一个 SecondViewController.swift 文件。

ViewController.swift 实例仍然存在,对吗?

所以现在,从 SecondViewController.swift 开始,我调用 ViewController().someFunction()

没有调用 ViewController 的 "viewDidLoad",只调用了我专门调用的函数。

现在:如果我在 ViewController.swift "var testNum = 2" 和 ViewController 的 viewDidLoad 中实例化一个 Int 变量,我将其值更改为 14。然后我转到 SecondViewController.然后我调用 ViewController().someFunction() 并在该函数中打印 testNum 的值,我得到实例化值 2 而不是 ViewController 的值 14,这导致我相信我已经通过以这种方式调用函数创建了 ViewController 的新副本。

是吗?那是我所做的吗?如果是这样,有没有办法在现有的 ViewController 中调用一个函数,而不是从 SecondViewController.swift 中创建一个新的 ViewController?

谢谢!

如果您要存储值,我建议您创建一个模型 class。

https://developer.apple.com/library/ios/documentation/General/Conceptual/DevPedia-CocoaCore/MVC.html

这将使数据独立于控制器,因为要回答您的 "The ViewController.swift instance is still in existence, correct?" 问题,它可能存在也可能不存在,具体取决于内存。这就是为什么创建模型是可取的,因为那样你就不用担心了。

如果您想要示例,如果您google MVC iOS,网上有很多示例。希望对您有所帮助。

I have my ViewController.swift which is the first to run when the app loads. I then segue to another SecondViewController.swift file.

吹毛求疵:您不在 'files' 之间切换,而是在这些文件中定义的 classes 实例之间切换。

The ViewController.swift instance is still in existence, correct?

是的。嗯,那个文件中定义的 class 的原始实例,见上文。

So now, from SecondViewController.swift, I call ViewController().someFunction()

The ViewController's "viewDidLoad" does not get called, only the function I specifically called to.

使用 ViewController() 可以创建 ViewController class 的新实例,然后直接在其上调用该方法。这没有多大意义。

Now: if I instantiate an Int variable in ViewController.swift "var testNum = 2" and in the ViewController's viewDidLoad I change its value to 14. Then I segue to SecondViewController. Then I call to ViewController().someFunction() and I print the value of testNum in that function, I get the instantiated value of 2

当您调用 ViewController() 时,您创建了 ViewController.swift 中定义的 class 的 new 实例。很(非常)可能这不是您想要做的。 看来您更想保留那个 VC 的原始实例。所以你需要在做segue的时候转移它。

我确定您已经阅读了 View Controller Programming Guide for iOS,对吧? ;-) 这是一个相关部分:

The prepareForSegue:sender: method of the source view controller lets you pass data from the source view controller to the destination view controller. The UIStoryboardSegue object passed to the method contains a reference to the destination view controller along with other segue-related information.

通常你不想保留对原始视图控制器的引用,而是将相关数据从它传输到你继续的VC(以分离它们)。