访问从另一个类调用的函数中的变量

时间:2017-04-18 07:19:32

标签: ios swift

我有一个class1,它有很多变量,并且在class1中也有一个函数。我从另一个类class2.function调用函数但是我无法访问class1的变量。

这是示例代码

class ViewController: UIViewController {

   var Flat:String?
    var Flong:String?
    var Tlat:String?
    var Tlong:String?
    override func viewDidLoad() {
        super.viewDidLoad()

     Flat = "flat value";
    Flong="flong value";
    Tlat="Tlat value";
    Tlong="tlong value";

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func calculation()
    {
       print("origin_lat new\(Flat)")
        print("origin_lng new\(Flong)")
        print("dest_lat new\(Tlat)")
        print("dest_lng new\(Tlong)")
    }

}

我从另一个类Collectionviewcell点击函数

调用计算方法
var mycontroller : ViewController = ViewController()

  mycontroller.calculation()

为什么我无法访问任何人帮助我的值?

3 个答案:

答案 0 :(得分:1)

您还可以通过以下方式定义全局变量来访问其他控制器的变量:

class Class1ViewController: UIViewController {
    struct GlobalVariables{
        static var Flat:String?
        static var Flong:String?
        static var Tlat:String?
        static var Tlong:String?
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        Flat = "flat value";
        Flong="flong value";
        Tlat="Tlat value";
        Tlong="tlong value";
    }
  ...
}

您可以在另一个视图控制器中使用这些变量:

class Class2ViewController: UIViewController 
{
 ...
    print(Class1ViewController.GlobalVariables.Flat)
    print(Class1ViewController.GlobalVariables.Flong)
    print(Class1ViewController.GlobalVariables.Tlat)
    print(Class1ViewController.GlobalVariables.Tlong)
 ...
}

答案 1 :(得分:1)

实际上," viewDidLoad()"函数未被调用。当你显示viewController时会调用它,例如,UINavigationController推送它。在您的情况下,您刚刚创建了viewController,而不是显示它。如果要在不显示viewController的情况下初始化这些变量,则需要执行以下操作:

class ViewController: UIViewController {

    var Flat:String?
    var Flong:String?
    var Tlat:String?
    var Tlong:String?

    required init?(coder:NSCoder) {
        super.init(coder:coder)
        self.customInit()
    }

    override init(nibName: String?, bundle: Bundle?) {
        super.init(nibName: nibName, bundle: bundle)
        self.customInit()
    }

    func customInit() {
        Flat = "flat value";
        Flong="flong value";
        Tlat="Tlat value";
        Tlong="tlong value";
    }

    //.......
} 

答案 2 :(得分:0)

您尝试实现的是一种模型类。我建议你创建一个简单的模型类,它不是UIViewcontroller的子类,就像这样。

class Model: NSObject {
   var fLat: String?
   var fLong: String?
   var tLat: String?
   var tLong: String?

override init() {
    super.init()

    fLat = "flat value"
    fLong = "flong value"
    tLat = "tlat value"
    tLong = "tlong value";
}



// for print I have forced unwrapped so remember to check before force unwrapping smi)e
func calculation() {
    print("orgin_lat new\(fLat!)")
    print("origin_lng new\(fLong!)")
    print("origin_lat new\(tLat!)")
    print("origin_lng new \(tLong!)")
  }


}

现在在您的主View控制器中,您可以初始化并调用函数,如此

let model = Model()
model.calculation()