【发布时间】:2016-12-01 21:13:20
【问题描述】:
我正在解析来自 iTunes Store 的 JSON 以检索有关音乐家的信息。在解析我收到这样的字典时,它正在打印到我的控制台。
"resultCount": 50
这是我返回对象的方法。但是字典包含50多个元素,程序只返回字典的一个元素。
extension SearchViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if !hasSearched {
return 0
}
else if searchResults.count == 0 {
return 1
} else {
return searchResults.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if searchResults.count == 0 {
return tableView.dequeueReusableCell(withIdentifier: TableViewCellIdentifires.nothingFoundCell, for: indexPath)
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: TableViewCellIdentifires.searchResultCell, for: indexPath) as! SearchResultCell
let searchResult = searchResults[indexPath.row]
cell.nameLabel.text = searchResult.name
if searchResult.artistName.isEmpty {
cell.artistNameLabel.text = "Unknown"
} else {
cell.artistNameLabel.text = String(format: "%@ (%@)", searchResult.artistName, kindForDisplay(kind: searchResult.kind))
}
return cell
}
}
func kindForDisplay(kind: String) -> String {
switch kind {
case "album": return "Album"
case "audiobook": return "Audio Book"
case "book": return "Book"
case "ebook": return "E-Book"
case "feature-movie": return "Movie"
case "music-video": return "Music Video"
case "podcast": return "Podcast"
case "software": return "App"
case "song": return "Song"
case "tv-episode": return "TV Episode"
default: return kind
}
}
extension SearchViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
if searchResults.count == 0 {
return nil
} else {
return indexPath
}
}
}
这个方法是不是我写错了,还是应该仔细看看其他的?
【问题讨论】:
-
你是如何初始化
searchResults的?从您的代码的外观来看,它可能会找到searchResults.count = 0并在numberOfRows方法中返回 1。
标签: ios json uitableview dictionary