1

I've got an array of objects in ViewControllerA that need to be passed to ViewControllerE, which happens to be a view controller that is "several segues away." In other words, I cannot use a segue to pass my data. I've also tried using the protocol/delegate pattern, but realized that it's only for passing BACK data. In this case, I'm trying to pass FORWARD data.

Does anyone have advice on what I should do to get my data from VC-A to VC-E?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Grant Park
  • 1,004
  • 1
  • 9
  • 29

2 Answers2

0

Your question is already your answer, make it global, create a singleton class that hold the array of objects, then pass value to it and use it anywhere u want in your app

class Data {
    static let sharedData = Data()
    var array = [Object]()
}

In VC-A :

Data.sharedData.array = yourArray

Then retrieve it anywhere with let array = Data.sharedData.array

Tj3n
  • 9,837
  • 2
  • 24
  • 35
  • 1
    This feels so dirty though...Is it safe? – Grant Park Jan 07 '16 at 04:35
  • Well its the fastest and quickest way...I don't really see the reason for unsafe unless its jailbreak phone and u don't save it in your app documents/hard disk/etc.. – Tj3n Jan 07 '16 at 04:39
  • 3
    Don't accept this answer, it's bad advice. Your data shouldn't be a singleton or global. It may be fast and quick but that doesn't make it the correct approach. – rmaddy Jan 07 '16 at 04:48
  • Can you point me towards a better direction? What's the appropriate measure? – Grant Park Jan 07 '16 at 20:32
  • After reading this, it seems like making my data global isn't too bad of a decision. It's really the only case in my app where I need to use a global. I know not to abuse this pattern, so I feel like it would be okay. http://stackoverflow.com/questions/34475935/when-to-use-global-variables-in-swift – Grant Park Jan 07 '16 at 21:20
  • @rmaddy what would be a better solution? – Alex Feb 05 '16 at 07:50
0

Store in preference and use when needed. like that,

VC-A let prefs: NSUserDefaults = NSUserDefaults.standardUserDefaults() prefs.setValue("YOURVALUE", forKey: "YOURKEYNAME")

VC-E let prefs: NSUserDefaults = NSUserDefaults.standardUserDefaults() prefs.valueForKey("YOURKEYNAME")

May be this is helpful. :)

Rushabh Shah
  • 396
  • 3
  • 19