Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
272 views
in Technique[技术] by (71.8m points)

ios - Access variable in a function which is called from another class

I have a class1 which is having many variable and also having one function within a class1.I am calling the function from another class class2.function triggered but i cannot access variable of class1.

here is the sample code

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)")
    }

}

I am calling calculation method from another class Collectionviewcell click function

var mycontroller : ViewController = ViewController()

  mycontroller.calculation()

Why i could not access the values anyone help me?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can also reach other controller's variables with defining global variables like this way:

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";
    }
  ...
}

And you can use these variables in another view controller:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...