[英]How can I reference instances of other classes, both ways without crashing?
I have a simple question that I have trouble finding the answer two. 我有一个简单的问题,我很难找到答案二。 The code below crash.
下面的代码崩溃。 From debug it seems to come from a loop, I think it is because I reference the other class in both classes.
从调试看来,它似乎来自循环,我认为这是因为我在两个类中都引用了另一个类。 Can someone please explain what is going on and if possible show how I can have both classes talk to each other (both ways)?
有人可以解释发生了什么吗?如果可以,请说明我如何让两个班级互相交流(两种方式)? Any help would be very much appreciated !
任何帮助将不胜感激! Thank you.
谢谢。
View Controller One
查看控制器一
import UIKit
class ViewControllerOne: UIViewController{
let doSomething = DoSomething()
var one = "test"
@IBAction func buttonTapped(sender: AnyObject) {
doSomething.functionTwo()
}
}
Do Something This Crash
做这种崩溃
import UIKit
class DoSomething: NSObject {
let viewControllerOne = ViewControllerOne()
func functionTwo() -> String{
var two = viewControllerOne.one
return two
}
}
Do Something This works
做某事
import UIKit
class DoSomething: NSObject {
func functionTwo() -> String{
let viewControllerOne = ViewControllerOne()
var two = viewControllerOne.one
return two
}
}
In the first instance the initializer of DoSomething
has to create a ViewControllerOne
. 在第一个实例中,
DoSomething
的初始化程序必须创建一个ViewControllerOne
。 Since the initializer of ViewControllerOne
creates DoSomething
they loop infinitely. 由于
ViewControllerOne
的初始化程序创建了DoSomething
因此它们会无限循环。 In the second instance DoSomething
doesn't create until functionTwo()
is called, so there is no loop. 在第二种情况下,
DoSomething
直到functionTwo()
才会创建,因此没有循环。 You can have them talk to each other for example this way: 例如,您可以让他们互相交谈:
import UIKit
class ViewControllerOne : UIViewController
{
let doSomething = DoSomething()
var one = "test"
override func viewDidLoad()
{
super.viewDidLoad()
doSomething.viewControllerOne = self
}
@IBAction func buttonTapped(sender: AnyObject)
{
doSomething.functionTwo()
}
}
class DoSomething: NSObject
{
weak var viewControllerOne : ViewControllerOne?
func functionTwo() -> String
{
return viewControllerOne?.one ?? String()
}
}
-- -
So this is how it works in steps: 所以这是分步进行的:
self
in Swift is similar to this
in other languages self
斯威夫特类似于this
的其他语言 functionTwo
is called, it either returns the value of one
or if the viewControllerOne is nil it returns an empty String functionTwo
,它要么返回值one
要么如果viewControllerOne为nil则返回一个空字符串。 Classes never talk. 上课永远不会说话。 They are blueprints.
它们是蓝图。
You mean instances of a class that need to communicate. 您的意思是需要通信的类的实例。 Two ways: either each instance has a reference to the other instance or instances send messages to a third object that act as postmaster.
两种方式:每个实例都具有对另一个实例的引用,或者实例将消息发送到充当邮局主管的第三个对象。 See NSNotification for details how to communicate within apps without knowing the other objects by reference.
有关如何在应用程序内进行通信而不通过引用了解其他对象的详细信息,请参见NSNotification。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.