在多个ViewControllers

时间:2015-10-19 08:52:10

标签: ios swift

我对Swift的开发还很陌生,而且我似乎正在努力解决其中一个关键概念。

我希望在不同的UIViewControllers之间传递数据,允许所有人访问和操作它。

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

我在AppDelegate中初始化商店:

var itemStore = ItemStore()

然后我创建了第一个UIViewController并传入商店,以便它可以访问它:

FirstViewController(itemStore: ItemStore)

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

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

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

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

有什么建议吗?

1 个答案:

答案 0 :(得分:2)

您可以使用这样的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

已编辑添加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