2

I want to share some data (an array of custom objects) from different ViewController, when tab changed.

enter image description here

1 = TabController
2 = ViewController
3 = ViewController
4 = SplitViewController
5 = MapView
6 = ViewController
7 = TableViewController

I want to share data between: 7 to 3, 7 to 2

What is the best way to do this?

altocumulus
  • 21,179
  • 13
  • 61
  • 84
Flo
  • 1,179
  • 3
  • 15
  • 43

3 Answers3

2

You could do something like this:

class DataSource {

    static let sharedInstance = DataSource()

    var data: [AnyObject] = []

}

Usage:

DataSource.sharedInstance.data
Laffen
  • 2,753
  • 17
  • 29
1

Another simple solution is creating a view bag to hold data to be shared between VC:

import Foundation

class ViewBag
{
    internal static var internalDictionary = Dictionary<String, AnyObject>()

    class func get(key: String) -> AnyObject?
    {
        return internalDictionary[key]
    }

    class func add(key: String, data: AnyObject)
    {
        internalDictionary[key] = data
    }
}

class MyClass
{

}

// Example

let myClassArray = [MyClass(),MyClass(),MyClass(),MyClass()]

ViewBag.add("myKey", data: myClassArray)

ViewBag.get("myKey")?.count // You must do a proper casting here
brduca
  • 3,573
  • 2
  • 22
  • 30
0

What's the data?A string?NSNotification is best.A few data?Save to NSUserDefaults.A lot of data?Save to file and read it. Here is example code for find vc along view controller chain:

let vc7 = UIViewController()
let tabBarVC = vc7.splitViewController?.tabBarController
let vc2 = tabBarVC?.viewControllers?[1]
let vc3 = tabBarVC?.viewControllers?[2]
Lumialxk
  • 6,239
  • 6
  • 24
  • 47
  • 1
    Thats not helpful at all to throw around some nice keywords. Additionally is never a good idea to work around with NSUserDefaults for this kind of use case – glace Apr 08 '16 at 08:24
  • You can also get 3/2 along view controller chain.First,get split vc.Second,get tab bar vc.Last,get 2/3 in tab bar vc's `viewControllers`. – Lumialxk Apr 08 '16 at 08:25
  • An array of custom objects – Flo Apr 08 '16 at 08:27
  • @glace I know.But his question was not very clear and I updated my answer. – Lumialxk Apr 08 '16 at 08:32
  • @Lumialxk Can u please explain a little bit more i am a rookie on swift/ios – Flo Apr 08 '16 at 08:41