重用表视图变量Swift

时间:2014-12-23 21:56:25

标签: ios iphone uitableview swift

以下是表格视图:

   public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        var rowData: NSDictionary = self.tableData[indexPath.row] as NSDictionary
           let too: AnyObject = rowData ["time"] as NSString
        var name: String = rowData["time"] as String
        var formattedPrice: String = rowData["date"] as String

        var alert: UIAlertView = UIAlertView()
        alert.title = name
        alert.message = formattedPrice
        alert.addButtonWithTitle("Ok")
        alert.show()
         println ("hi")
         println (too)   
    }

我需要在另一个视图控制器中引用这些变量。我无法在上面说明这一点:

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

我试图阻止单击鼠标。     来自http://jamesleist.com/ios-swift-passing-data-between-viewcontrollers/

1 个答案:

答案 0 :(得分:0)

如果它不是很多数据,我用来在视图控制器之间传递数据的策略是将值存储在NSUserDefaults中。

设置值:首次获取数据时,请将其存储在NSUserDefaults

let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults() //This class variable needs to be defined every class where you set or fetch values from NSUserDefaults
public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    var rowData: NSDictionary = self.tableData[indexPath.row] as NSDictionary
    let too: AnyObject = rowData ["time"] as NSString
    var name: String = rowData["time"] as String
    var formattedPrice: String = rowData["date"] as String
    defaults.setObject(rowData, forKey: "rowData")
    defaults.setObject(too, forKey: "too")
    defaults.setObject(name, forKey: "name")
    defaults.setObject(formattedPrice, forKey: "formattedPrice")
    defaults.synchronize() //Call this after you're done editing defaults, it saves your change to the disk

    var alert: UIAlertView = UIAlertView()
    alert.title = name
    alert.message = formattedPrice
    alert.addButtonWithTitle("Ok")
    alert.show()
     println ("hi")
     println (too)   
}

获取值:当您需要获取值时,只需从NSUserDefaults抓取它。

let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
defaults.dictionaryForKey("rowData") as? NSDictionary
defaults.objectForKey("too") as? String
defaults.objectForKey("name") as? String
defaults.objectForKey("formattedPrice") as? String

这样做可以让您访问任何类中的存储值,并允许数据在应用关闭并重新打开后保持不变。如果您想在应用关闭后清除数据,请在AppDelegate applicationWillTerminate(application: UIApplication)函数中为以前设置的每个键调用removeObjectForKey函数。

let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
defaults.removeObjectForKey("rowData")
defaults.removeObjectForKey("too")
defaults.removeObjectForKey("name")
defaults.removeObjectForKey("formattedPrice")
defaults.synchronize()

有关NSUserDefaults的有用资料

NSUserDefulats课程参考:链接here