【发布时间】:2016-10-27 01:38:19
【问题描述】:
我知道如何使用基于特定键的 JSON 数据填充表视图,但我试图弄清楚如何仅将数据放入表视图中,如果它在键值中有特定值对。
具体来说,我的 JSON 文件包含一个键值对,即: “位置”:“伊利诺伊州芝加哥”, “大陆”:“美国”
我希望我的表格视图显示具有“美国”大陆值的任何条目的位置,并且我不希望它显示具有与其关联的不同大陆的任何位置。
我能得到任何帮助将不胜感激。这是我的 parseJSON 文件中的内容,但目前无法执行我想做的事情。我在 tableview 函数中得到一个超出范围的数组索引
func parseJSON(){
do{
let data = NSData(contentsOfURL: NSURL(string: "https://jsonblob.com/api/jsonBlob/580d0ccce4b0bcac9f837fbe")!)
let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
for anItem in jsonResult as! [Dictionary<String, AnyObject>]{
let mifiContinent = anItem["continent"] as! String!
if var mifiContinent = jsonResult["US"]{
let mifiLocation = anItem["location"] as! String
let newLocation = Location(location: mifiLocation)
locationOfMifi.append(newLocation)
}
}
}
catch let error as NSError{
print(error.debugDescription)
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCellWithIdentifier("LocationCell", forIndexPath: indexPath)as? LocationCell{
let location: Location!
location = locationOfMifi[indexPath.row]
cell.configureCell(location)
return cell
} else{
return UITableViewCell()
}
}
【问题讨论】:
-
您可能会遇到超出范围的错误,因为您在
cellForRowAtIndexPath中使用的locationOfMifiarray 不知何故与您的表数据源不一致。你能也展示你的numberOfRowsInSection方法吗? -
好吧,这听起来像是 CoreData 的完美工作。您必须创建一个数据模型,该模型具有与您的兴趣点相关的所有属性。在你的情况下,那将是大陆。然后,您可以告诉 CoreData 为您获取任何以北美为大陆的东西。使用 CoreData 而不仅仅是一个 Array 将为您的代码创造奇迹。
标签: json swift uitableview