您应该使用委托协议。欲了解更多信息,请查看this https://developer.apple.com/library/ios/documentation/General/Conceptual/CocoaEncyclopedia/DelegatesandDataSources/DelegatesandDataSources.html文档。
设置一个protocol
in the secondClass
,紧接着import
声明,像这样:
protocol InformingDelegate {
func valueChanged() -> CGFloat
}
里面一样secondClass
创建一个delegate
变量(有人建议它应该标记为weak
):
var delegate: InformingDelegate?
然后,创建一些您将访问更改后的值的方法。您可以将其分配给value
例如:
func callFromOtherClass() {
value = self.delegate?.valueChanged()
}
这是为了secondClass
。现在到firstClass
.
这里只需要符合协议就可以添加InformingDelegate
在类定义之后,如下所示:
class firstClass: UIViewController, InformingDelegate {
...
}
然后,通过创建另一个类的实例并将您自己设置为委托,通知编译器您将成为另一个类的委托:
var secondVC : secondClass = secondClass()
secondClass.delegate = self
secondClass.callFromOtherClass() // This will call the method in the secondClass
// which will then ask its delegate to trigger a method valueChanged() -
// Who is the delegate? Well, your firstClass, so you better implement
// this method!
最后一件事是通过实现其方法来实际遵守协议:
func valueChanged() -> CGFloat {
return myVariable // which is 5 in your case (value taken from a question)
}
这将分配myVariable
值(本例中为 5)value
在另一个班级。