【问题标题】:Accessing/passing common data between multiple ViewControllers在多个 ViewController 之间访问/传递公共数据
【发布时间】:2015-10-19 08:52:09
【问题描述】:

我对使用 Swift 进行开发还很陌生,我似乎在为其中一个关键概念而苦恼。

我希望在不同的 UIViewController 之间传递数据,让它们都可以访问和操作它。

例如,在我的应用程序中,我创建了一个包含项目数组的简单数据存储类。我希望所有 ViewController 都可以访问这个数组。

我在 AppDelegate 中初始化存储:

var itemStore = ItemStore()

然后我创建第一个 UIViewController 并传入 store 以便它可以访问它:

FirstViewController(itemStore: ItemStore)

为此,我需要对 FirstViewController 的 init 进行更改,以便它能够接受 itemStore 作为参数。

然后我想将该数据传递给 SecondViewController,然后再传递给 ThirdDataController。

我似乎没有必要编辑每个 UIViewController 类,以便它接受 itemStore 作为参数。

我在这里有什么选择?有些人告诉我将数据存储为 AppDelegate 的属性,以便所有人都可以访问它。但是,这似乎不是正确的做法。

有什么建议吗?

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    您可以使用这样的 segue 传递数据:

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
        if (segue.identifier == “segueTest”) {
    
            var svc = segue.destinationViewController as secondViewController;
    
            svc.toPass = textField.text
        }   
    }  
    

    另一种解决方案

    class AnsViewController: UIViewController {
       var theNum: Int
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            println(theNum)
        }
    
    }
    
    override func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
        let viewController = self.storyboard.instantiateViewControllerWithIdentifier("ansView") as AnsViewController
        viewController.num = theNum
        self.presentViewController(viewController, animated: true, completion: nil)
    }
    

    带有教程的完整演示解决方案可能对您有所帮助。

    Tutorial

    edited 添加了保存数据的 NSUserDefault 解决方案

    let highscore = 1000
    let userDefaults = NSUserDefaults.standardUserDefaults()
    userDefaults.setValue(highscore, forKey: "highscore")
    userDefaults.synchronize() // don't forget this!!!!
    
    Then, when you want to get the best highscore the user made, you have to "read" the highscore from the dictionary like this:
    
    if let highscore = userDefaults.valueForKey("highscore") {
        // do something here when a highscore exists
    }
    else {
        // no highscore exists
    }
    I hope this helps!
    

    NSUserDefaults 支持以下数据类型:

    NSString NSNumber NSDate NSArray NSDictionary NSData

    这里是Complete Demo Code, might be helpful to you

    【讨论】:

    • 这样会将下一个 ViewController 的属性设置为您传递的数据。但是,对我来说,您必须一次又一次地传递它似乎很奇怪(如果您从 AViewController 转到 BViewController 再到 CViewController)。有没有办法全局访问?
    • @BrianMarsh 是的,只需在顶层声明它。如果您希望它仅在这两个视图控制器中可用,请将它们放在同一个 swift 文件中,并在此文件的顶层声明您 var 私有
    • @BrianMarsh,您也可以将其保存在 UserDefault 上。或本地数据库或 .Plist 文件中.. 有很多方法。这里我给了你最简单的实现方式。
    • @LeoDabus - 对不起,你说在顶层声明是什么意思?
    • @BrianMarsh 在导入语句后在课堂外
    猜你喜欢
    • 1970-01-01
    • 2017-12-27
    • 2016-03-24
    • 2017-01-22
    • 2019-12-05
    • 1970-01-01
    • 1970-01-01
    • 2021-05-12
    • 1970-01-01
    相关资源
    最近更新 更多