1

I am interested in storing data in a sperate class, to allow this data to be saved and accessed from any view in the application. To do this, I first created an empty class in my project called GlobalData.swift. In this file I have the source code below:

import UIKit

    class Main {  
        var drinkData:PFObject?
        init(drinkData:PFObject) {
            self.drinkData = drinkData
        }
    }

In my Table View, when a user selects a cell I am doing save Parse PFObject so it can be easily accessed later on. In my Table class I have the following code:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    if let indexPath = self.tableView.indexPathForSelectedRow {
        let row = Int(indexPath.row)

        let localDrinkData = Main(drinkData:(objects?[row] as PFObject!))

        print("global : \(localDrinkData.drinkData)")

    }
} 

Now this works perfectly. The print line will do exactly what I want it to do (print out the PFObject and all items inside this row), the problem is I need to save this and then be able to access it in a different class.

My question remains. How can I call the Main drinkData in a different class and be able to print it exactly like I did in the function above:

print("global : \(localDrinkData.drinkData)")

Here is where I got the original source code for this design. Obviously, I made a few modifications: Access variable in different class - Swift

Thank you very much!

Community
  • 1
  • 1

1 Answers1

0

The only way that you would be able to access the same data from your class Main() would be to pass the instance of Main() that you're changing around. If you wanted to access Main() from other classes without needing to pass around your Main() instance, I would recommend turning Main() into a Singleton class.

import UIKit

class Main {
    static let sharedMain = Main()
    var drinkData:PFObject?
}

And if you want to set/access data in main, it would look like this:

Set: Main.sharedMain.drinkData = //insert PFObject

Read: let sharedData = Main.sharedMain.drinkData

Side note: I would recommend you change the name of your class to maybe "DrinkManager", it feels wrong having custom classes called Main.

Eytan Schulman
  • 566
  • 2
  • 4
  • 20