乐趣区

关于ios:iOS-NSDictionary-write-to-path-什么时候失效

let src = json as NSDictionary
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let path = documentsURL.appendingPathComponent("one.plist")
let result = src.write(to: path, atomically: false)
print(result, path)

生效了,

写入失败,

为什么?


当然不是代码的问题,是数据的问题

数据长这样


json:
{
  "message" : "","code": 200,"state": null,"data": {"author":"",
    "next_id" : 409,
    "title" : "2 金木水火土",
    "prev_id" : 405,
    "list" : [
      {
        "string" : "识字",
        "type" : 0
      },
      {
        "string" : "一:一个 一群",
        "type" : 1,
        "pronounce" : "yī"
      }
    ],
    "nodes" : {
      "wav_lengths" : [
        0,
        4.0049999999999999,
        8.2509999999999994
      ],
      "node" : [
        {
          "index" : 0,
          "title" : "识字"
        }
      ]
    },
    "audio" : "http://ss-cn.aliyuncs.com/chinese_audio%2F%E9%83%A8%E7%BC%96%E7%89%88%E8%AF%AD%E6%96%87%E5%85%AD%E4%B8%89%E5%88%B6%2F%E4%B8%80%E5%B9%B4%E7%BA%A7%E4%B8%8A%E5%86%8C%2Faudio%2F%E8%AF%86%E5%AD%972.wav?OSSAccessKeyId=LTAIQ8Lif1HHVkXd&Expires=1606364958&Signature=XC%2Fm%2BLKZ30b%2FVYCsXrwCaNj6nZI%3D"
  }
}

数据是字典,但不合乎 plist 的标准



 {
        "string" : "识字",
        "type" : 0
      },
      {
        "string" : "一:一个 一群",
        "type" : 1,
        "pronounce" : "yī"
      }

list 外面是数组,数组装字典,

一个字典三个键,一个字典两个键,

所以呵呵


批改代码:

 let resp = try Base.decoder.decode(GeneralSingle<P_intelligence>.self, from: data)
      var newPlistModel = resp
      var i = 0
      let count = resp.data.list.count
      while i < count{if resp.data.list[i].pronounce == nil{newPlistModel.data.list[i].pronounce = "hehe"
          }
          i += 1
       }
       let json = newPlistModel.data.dictionary
       let src = json as NSDictionary
       let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
       let path = documentsURL.appendingPathComponent("one.plist")
       let result = src.write(to: path, atomically: false)
       print(result, path)
       

对应的模型:

struct P_intelligence: Codable {
    
    let listen: String
    
    let see: Node_intelligence
    
    
    var list: [Moron]
    
    let title: String
    
    
    let pre: Int
    
    let next: Int
    let author: String?
    
    
    private enum CodingKeys : String, CodingKey {
        case listen = "audio", see = "nodes"
        case list,  title, pre = "prev_id"
        case next = "next_id", author
    }
    
    
    var dictionary: [String: Any] {return (try? JSONSerialization.jsonObject(with: JSONEncoder().encode(self))) as? [String: Any] ?? [:]
    }
}



struct Moron: Codable {
    let string: String
    let type: Int
    var pronounce: String?
}


// ......
退出移动版