iOS sharing data between viewcontrollers

2019-07-07 19:42发布

问题:

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

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?

回答1:

You could do something like this:

class DataSource {

    static let sharedInstance = DataSource()

    var data: [AnyObject] = []

}

Usage:

DataSource.sharedInstance.data


回答2:

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


回答3:

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]