【问题标题】:NSArray with contents of file not work in ios带有文件内容的NSArray在ios​​中不起作用
【发布时间】:2015-02-14 11:50:53
【问题描述】:

我正在尝试从 iOS 中的 JSON 文件中获取 JSON 数组。问题是代码不起作用 JSON文件内容为:

[{a:"m",data:"1597,144",tick:1},{a:"m",data:"1595,144",tick:1}, ...]

这是我的 Swift 代码:

  if let filePath = NSBundle.mainBundle().pathForResource("data", ofType: "json") {
     let array = NSMutableArray(contentsOfFile: filePath)
     println("\(array)")
  }

该文件存在于路径中,但由于某种原因它无法正常工作。当我尝试打印数组时,我得到null。

【问题讨论】:

  • 来自文档:aPath The path to a file containing a representation of an array produced by the writeToFile:atomically: method. 也就是说 - 它只读取以这种方式创建的文件,而不是任意文本文件。
  • 谢谢您的回复,如果我想实现这个功能,我该怎么做? @Grimxn

标签: ios swift


【解决方案1】:

NSMutableArray(contentsOfFile: filePath) 仅适用于属性列表:

https://developer.apple.com/library/ios/documentation/General/Reference/InfoPlistKeyReference/Articles/AboutInformationPropertyListFiles.html

您拥有的是 JSON 字符串。如果要从 JSON 文件加载数组,请查看: How do I parse JSON from a file in iOS?

【讨论】:

  • 我尝试了Fetching/Parsing data from a json file in iOS中的代码,结果是返回错误Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (No string key for value in object around character 2.) UserInfo=0x1458ba90 {NSDebugDescription=No string key for value in object around character 2.可能在JSON文件中找不到key,JSON文件中的内容是一个数组
  • 我猜 JSON 键需要是字符串。尝试使用 jsonlint.com 验证您的 JSON
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-10
  • 1970-01-01
  • 2014-11-18
  • 1970-01-01
  • 2021-11-25
  • 1970-01-01
相关资源
最近更新 更多