如何将数组传递给nsuserdefaults并在tableview的一节中使用它们

时间:2016-12-08 06:04:42

标签: arrays json swift uitableview nsuserdefaults

这是我的数组

[
    {
        "Description" : null,
        "Message" : null,
        "vmanager_account" : "True",
        "user_id" : "174",
        "login_name" : "ssrikanth",
        "user_name" : "Surya Srikanth",
        "owner_id" : "1",
        "user_email" : "cserafimescu@vcomsolutions.com",
        "customer_id" : "20",
        "vmanager_cc" : "True",
        "vmanager_tp" : "True",
        "customer_name" : "vCom Solutions",
        "is_so" : "0"
    }
]

我需要在数组(nsuserdefaults)中存储“customer id”,“user_name”,“user_email”并将它们传递给另一个控制器(tableview部分)

// tableviewcontroller中NSUserdefaults的重新获取值。现在我需要在数组中传递这些值,并在第1节中显示tableview。

//Retreiving Username
    let defaults = UserDefaults.standard
    if  let usernameRetrieved = defaults.string(forKey: "userNameKey")
    {
        print("got username in side menu: \(usernameRetrieved)")

    }

    //Retreiving CustomerName
    let defaults1 = UserDefaults.standard
    if let customerNameRetrieved = defaults1.string(forKey: "customerNameKey")
    {
        print("got Customer Name in side menu: \(customerNameRetrieved)")

    }

    //Retreiving User Email Id
    let defaults2 = UserDefaults.standard
    if let emailIDRetrieved = defaults2.string(forKey: "userEmailKey")
    {
        print("got Email Id in side menu: \(emailIDRetrieved)")

    }

1 个答案:

答案 0 :(得分:0)

  

环境:Xcode 8和Swift 3.0

我根据您的要求创建了相同的结构。

let arrInfo: [Dictionary<String,Any>] =
                  [["Description":"Hello",
                    "Message":"Message",
                    "vmanager_account":"vmanager_account",
                    "user_id" : "174",
                    "login_name" : "ssrikanth",
                    "user_name" : "Surya Srikanth",
                    "owner_id" : "1",
                    "user_email" : "cserafimescu@vcomsolutions.com",
                    "customer_id" : "20",
                    "vmanager_cc" : "True",
                    "vmanager_tp" : "True",
                    "customer_name" : "vCom Solutions",
                    "is_so" : "0"]]

将数组存储在UserDefaults

    let userDefault = UserDefaults.standard
    userDefault.setValue(arrInfo, forKey: "storeArray")
    userDefault.synchronize()

UserDefaults

中检索数组
    if((UserDefaults.standard.array(forKey: "storeArray")) != nil){
        let getArray = (UserDefaults.standard.array(forKey: "storeArray") as! [Dictionary<String,Any>])

        let dict = getArray[0]
        print("Customer ID : ",dict["customer_id"])
    }

希望它适合你!!!