如果我的根是一个数组并且充满字典,那么 View Controller 1 就已设置
let path = Bundle.main.path(forResource:"Animals", ofType: "plist")
let dics = NSArray(contentsOfFile: path!) as! [NSMutableDictionary]
并且 viewcontroller 2 已设置
let path = Bundle.main.path(forResource:"Animals", ofType: "plist")
if FileManager.default.fileExists(atPath: path!){
let dics = NSArray(contentsOfFile: path!) as! [NSMutableDictionary]
dics.setValue(isFavorite, ForKey: "fav")
dics.write(toFile: path!, atomically: true)
我将 isFavorite 作为变量放在代码顶部,如果用户点击按钮,isFavorite 就会从 false 更改为 true,反之亦然。 isFavorite = !isfavorite.现在,如果我运行此代码,它会指出 NSMutableDictionary 没有成员 setValue 或 write。我不知道如何让系统知道我从 ViewController 1 中的 plist 中的数组中的字典列表中单击了第二个字典单元格,并且我想将具有“fav”的键值从 false 更改为 true ViewController 2。我知道这听起来有点令人困惑,所以让我重新表述一下。 ViewController 1 有一堆动物,狗、猫、鱼等。所以现在,如果用户单击 Cats,它会将它们带到 viewcontroller 2,而在 viewcontroller 2 上,我想要一个最喜欢的按钮,如果用户单击它,它会更新 Plist 文件和 bool 值cats 从 false 变为 true。我尝试使用 userDefaults 方法,如果我更改一种动物的 bool 值,它会更改所有动物。所以我在plist中的所有动物中又做了一个 bool 值的关键值。我希望当用户点击 ViewController 2 上的“收藏夹”按钮时更改 bool 值,但它不会保存到 plist 文件中。
更新:所以看看我的代码,我认为问题出在 ViewController 1 中。在 ViewController 1 上我写道:
let path = Bundle.main.path(forResource:"Animals", ofType: "plist")
let dics = NSArray(contentsOfFile: path!) as! [NSMutableDictionary]
self.orginalData = dics.map{Animals(Type: $0["Type"] as! String, Desc: $0["Desc"] as! String, fav: $0["fav"] as! Bool)}
self.filteredData = self.original Data
然后我将其显示在 ViewController 1 的 tableview 上,如下所示:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if isFiltering() {
searchFooter.setIsFilteringToShow(filteredItemCount: filteredData.count,
of: originalData.count)
return filteredData.count
}
searchFooter.setNotFiltering()
return originalData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
var animals : Animals
if isFiltering() {
animals = filteredData[indexPath.row]
} else {
animals = originalData[indexPath.row]
}
cell.textLabel?.text = Animals.Type
cell.detailTextLabel!.text = Animals.Desc
return cell
}
最佳答案
关于setValue
:您需要在字典上调用它,而不是数组。
关于write
:您需要转换为NSArray
,因为Swift.Array
不存在它。
它需要更接近这样的东西:
let isFavorite = true // based on user selection
let selectedIndex = 0 // this is the index of the animal selected in VC 1
if let path = Bundle.main.path(forResource:"Animals", ofType: "plist"),
FileManager.default.fileExists(atPath: path),
let dics = NSArray(contentsOfFile: path) as? [NSMutableDictionary] {
let selectedAnimal = dics[selectedIndex]
selectedAnimal["fav"] = isFavorite // this replaces `setValue`
(dics as NSArray).write(toFile: path, atomically: true)
}
关于swift - 将 Bool 值保存到 Plist 并更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48078386/