简体   繁体   English

快速使用带有NSUserDefaults的字典

[英]Using a dictionary with NSUserDefaults in swift

I'm trying to learn about dictionaries and nsusersdefaults in swift. 我正在尝试快速了解字典和nsusersdefaults。 I wrote a small program that creates a dictionary of strings and uses that dictionary to populate a tableview. 我编写了一个小程序,该程序创建一个字符串字典,并使用该字典填充表视图。 Next I save the dictionary to NSUserDefaults. 接下来,我将字典保存到NSUserDefaults。 Everything at this point is working great. 此时一切正常。 It's when I attempt to pull the dictionary back out and use it that things go wrong. 当我尝试撤回字典并使用字典时,出现了问题。

Here is my complete code, the error is on the line myDict = userDefaults and the error is Cannot assign a value of type '[String : AnyObject]' to a value of type '[Dictionary]': 这是我的完整代码,错误在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>()]

should be 应该

var myDict = [String:String]()

at least in swift 2.0 至少在Swift 2.0中

For your problem it should actually be 对于您的问题,它实际上应该是

var myDict = [String:AnyObject]()

because that is what you get from NSUserdefaults. 因为那是您从NSUserdefaults获得的。 When you access a value from a key in the dictionary you need to cast it to String. 当您从字典中的键访问值时,需要将其强制转换为String。

Instead of setObject use the sync method : 代替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