[英]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.