2015-10-19 37 views
0

我在Swift中開發相當新,而且我似乎正在努力解決其中一個關鍵概念。訪問/傳遞多個ViewControllers之間的公共數據

我正在尋找在不同的UIViewControllers之間傳遞數據,讓他們都可以訪問和操作它。

例如,在我的應用程序中,我創建了一個包含項目數組的簡單數據存儲類。我希望這個數組可以被所有ViewController訪問。

我初始化中的AppDelegate店:

var itemStore = ItemStore() 

然後我創建第一個UIViewController中,並通過在存儲,以便它可以訪問它:

FirstViewController(itemStore: ItemStore) 

因此,要做到這一點,我需要對FirstViewController的init進行更改,以便它能夠接受itemStore作爲參數。

然後,我想將該數據傳遞給SecondViewController,然後傳遞給ThirdDataController。

我似乎沒有必要編輯每一個UIViewController類,以便它接受itemStore作爲參數。

我在這裏有什麼選擇?有些人告訴我將數據存儲爲AppDelegate的一個屬性,以便所有人均可訪問。但是,這似乎不是正確的做法。

有什麼建議嗎?

回答

2

您可以使用賽格瑞這樣傳遞數據:

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

+0

因此,將下一個ViewController的屬性設置爲您傳遞的數據。然而,我覺得你必須一遍又一遍地傳遞它(如果你從AViewController到BViewController到CViewController),這似乎很奇怪。有沒有辦法在全球範圍內訪問它? –

+0

@BrianMarsh是的,只是在頂層聲明它。如果你希望它只在這兩個視圖控制器上可用,請將它們放在同一個swift文件中,並聲明你在這個文件的頂層隱藏了var private –

+0

@BrianMarsh,你也可以將它保存在UserDefault上。或本地數據庫或.Plist文件..有很多方法。在這裏我已經給你實現它的最簡單的方法。 – Mehul

相關問題