iOS sharing data between viewcontrollers

2019-07-07 19:03发布

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?

3条回答
Emotional °昔
2楼-- · 2019-07-07 19:34

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]
查看更多
The star\"
3楼-- · 2019-07-07 19:45

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
查看更多
趁早两清
4楼-- · 2019-07-07 19:54

You could do something like this:

class DataSource {

    static let sharedInstance = DataSource()

    var data: [AnyObject] = []

}

Usage:

DataSource.sharedInstance.data
查看更多
登录 后发表回答