这里我在xml中获取数据,并且已经检索到Dictionary
以加载tableView
。工作流程 - 当用户在主屏幕上并点击创建按钮并进入下一个搜索产品屏幕时,用户可以使用他们的亚马逊产品。搜索到的产品被加载到表格视图单元格中。
我的问题是当点击创建按钮tableView
尝试加载数据及其崩溃时
崩溃线是结果!.count。
这是我试过的代码:
var results: [[String: String]]?
var currentDictionary: [String: String]? // the current dictionary
var currentValue: String? // the current value for one of the
keys in the dictionary
let recordKey = "ItemAttributes"
let dictionaryKeys = Set<String>(["Title"])
func parserDidStartDocument(_ parser: XMLParser) {
results = []
}
// start element
//
// - If we're starting a "record" create the dictionary that will hold the results
// - If we're starting one of our dictionary keys, initialize `currentValue` (otherwise leave `nil`)
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
if elementName == recordKey {
currentDictionary = [:]
} else if dictionaryKeys.contains(elementName) {
currentValue = ""
}
}
// found characters
//
// - If this is an element we care about, append those characters.
// - If `currentValue` still `nil`, then do nothing.
func parser(_ parser: XMLParser, foundCharacters string: String) {
currentValue? += string
}
// end element
//
// - If we're at the end of the whole dictionary, then save that dictionary in our array
// - If we're at the end of an element that belongs in the dictionary, then save that value in the dictionary
func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
if elementName == recordKey {
results!.append(currentDictionary!)
currentDictionary = nil
} else if dictionaryKeys.contains(elementName) {
currentDictionary![elementName] = currentValue
currentValue = nil
}
}
// Just in case, if there's an error, report it. (We don't want to fly blind here.)
func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) {
print(parseError)
currentValue = nil
currentDictionary = nil
results = nil
}
// func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// return 1
// }
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return results!.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath as IndexPath) as! amazonProductListTableViewCell
let productlist = ProductName[indexPath.row]
print("prodic:::\(productlist)")
// cell.amazonProductTitle?.text = productlist[indexPath.row]
// cell.detailTextLabel?.text = book.bookAuthor
return cell
}
答案 0 :(得分:1)
永远不要将表视图数据源数组声明为可选。
如果在初始化数组之前调用numberOfRows
,则应用程序崩溃。
声明results
var results = [[String: String]]()
在parserDidStartDocument
以及parseErrorOccurred
中清除数组
results.removeAll()
请注意,每个展开的部队都会导致崩溃并且您使用了很多惊叹号!