将Bool值保存到Plist和更新

问题描述 投票:0回答:1

如果我的根是一个数组并且填充了字典,那么就设置了viewcontroller 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中点击了数组中字典列表中的第二个字典单元格,我想从false中将那个“fav”的键值更改为true ViewController 2.我知道这听起来有点令人困惑,所以让我重新说一下。 ViewController 1有一堆动物Dogs,Cats,Fish等。所以现在如果用户点击Cats它将它们带到viewcontroller 2和viewcontroller 2我想要一个喜欢的按钮,如果用户点击它它更新Plist文件和布尔值in猫从false变为true。我尝试使用userDefaults方法,如果我更改了一只动物的布尔值,它会改变所有动物。所以我在plist中的所有动物中创建了另一个布尔键值。我希望当用户点击ViewController 2上的收藏夹按钮时更改布尔值,但它不会保存到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
  }
swift save plist
1个回答
0
投票

关于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)
}
© www.soinside.com 2019 - 2024. All rights reserved.