簡體   English   中英

快速使用帶有NSUserDefaults的字典

[英]Using a dictionary with NSUserDefaults in swift

我正在嘗試快速了解字典和nsusersdefaults。 我編寫了一個小程序,該程序創建一個字符串字典,並使用該字典填充表視圖。 接下來,我將字典保存到NSUserDefaults。 此時一切正常。 當我嘗試撤回字典並使用字典時,出現了問題。

這是我的完整代碼,錯誤在myDict = userDefaults行上,錯誤是無法將類型[[String:AnyObject]]的值分配給類型[[Dictionary]]的值:

import UIKit


// Create dictionary
var myDict = [Dictionary<String,String>()]


class TableViewController: UITableViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    print(myDict.count)

    // Dictionary starts out with 1 item when new
    // so remove that one thing and create it if needed

    if myDict.count == 1 {

        myDict.removeAtIndex(0)

        // Put some stuff in the dictionary

        myDict.append(["name":"Bill","age":"39","sex":"male"])
        myDict.append(["name":"Nick","age":"8","sex":"male"])
        print(myDict)


    } else {

        if let userDefaults = NSUserDefaults.standardUserDefaults().dictionaryForKey("myDict") {

            myDict = userDefaults


        }

    }

}


override func viewDidAppear(animated: Bool) {
    NSUserDefaults.standardUserDefaults().setObject(myDict, forKey: "myDict")
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}



// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return myDict.count
}


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)

    // Configure the cell...

    cell.textLabel!.text = myDict[indexPath.row]["name"]

    return cell
 }
}
var myDict = [Dictionary<String,String>()]

應該

var myDict = [String:String]()

至少在Swift 2.0中

對於您的問題,它實際上應該是

var myDict = [String:AnyObject]()

因為那是您從NSUserdefaults獲得的。 當您從字典中的鍵訪問值時,需要將其強制轉換為String。

代替setObject使用sync方法

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];        
    if (![defaults objectForKey:@"vesselType_preference"])
    {
        [defaults setObject:@"Dry" forKey:@"vesselType_preference"];
    }
    [[NSUserDefaults standardUserDefaults] synchronize];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM