简体   繁体   中英

Accessing class instance in swift

I've got a Graph class which is an UIView and I'm initializing it inside mainVC.swift :

class MainVC : UIViewController{
   let graph : Graph!

   override func viewDidLoad(){
      super.viewDidLoad()
      let data_x : [Double] = [...]
      let data_y : [Double] = [...]
      ...
      graph = Graph(frame: CGRect(...), color: ..., xData: data_x, yData: data_y, darkMode: ...)
      view.addSubview(graph)
      ...
      }

Now I would like to access function inside instance of the class which I've created in MainVC in different class (to populate data in TableView).

var g : Graph = MainVC.graph returns "Instance member graph cannot be used on type MainVC" I've also tried using static variable but there was an error.

This is one of the way which i known check it out.

class MainVC {
   let graph : Graph! 
}

graph is a stored property is a constant or variable that is stored as part of an instance of a particular class .So you tried for accessing instance property not an instance of class.

In your class MainVC make variable as static which holds instance

 static var graph: Graph?

Then store instance of Graph in graph property in Graph class

  MainVc.graph = self

Now you can use in another class where you access graph instance like

  MainVc.graph

您正在访问一个类的实例变量,而不是它的实例。

let mainVc = MainVC()
let graph = self.graph

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM