gpt4 book ai didi

将方法外包给静态方法时出现 Swift 错误

转载 作者:行者123 更新时间:2023-11-30 12:16:43 27 4
gpt4 key购买 nike

我想开始使用 Swift 编写我的 Android 应用程序。应用程序应使用 url 中的 xml 来显示对象列表。

UITableViewController 中的解析和显示已经开始工作。现在我想将解析外包到一个静态类中,每当我想要获取对象列表时都可以使用它。

问题是,当我使用外包类时,我收到 EXC_BAD_ACCESS 错误。我认为问题可能是,我正在尝试访问已释放的内存,但我不确定。

下面您可以找到我正在使用的代码:

XML(简化):

<result>
<row>
<id>1</id>
<name>Alpha</name>
</row>
<row>
<id>2</id>
<name>Beta</name>
</row>
<row>
<id>3</id>
<name>Gamma</name>
</row>
</result>

XMLHelper.swift(外包类,使用外包类ToolXMLParserDelegate.swift):

import Foundation

class XMLHelper : NSObject{

static var baseURL = "{myServerUrl}" // not public for security reasons
static var toolListString = "getToolList.php"

class func getToolList() -> [Tool]? {
var toolList: [Tool] = []

let url = baseURL+toolListString

guard let myURL = URL(string: url) else {
print("URL not defined properly")
return nil
}
guard let parser = XMLParser(contentsOf: myURL as URL) else {
print("Cannot Read Data")
return nil
}

parser.delegate = ToolXMLParserDelegate(toolList: &toolList)

if !parser.parse() { //HERE I GET THE ERROR
print("Data Errors Exist:")
let error = parser.parserError!
print("Error Description:\(error.localizedDescription)")
//print("Error reason:\(error.localizedFailureReason)")
print("Line number: \(parser.lineNumber)")
}

return toolList
}
}

ToolXMLParserDelegate.swift:

import Foundation

class ToolXMLParserDelegate : NSObject, XMLParserDelegate {

var tools: [Tool] = []
var eName: String = String()
var toolId = String()
var toolName = String()

init(toolList : inout [Tool]) {
self.tools = toolList
}


func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
eName = elementName
if elementName == "row" {
toolId = String()
toolName = String()
}
}


func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
if elementName == "row" {

let tool = Tool()
tool.id = Int(toolId)!
tool.name = toolName
tools.append(tool)
}
}


func parser(_ parser: XMLParser, foundCharacters string: String) {
let data = string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)

if (!data.isEmpty) {
if eName == "id" {
toolId += data
} else if eName == "name" {
toolName += data
}
}
}
}

工具.swift:

import UIKit

class Tool: NSObject {

var id: Int = Int()
var name: String = String()

override init() {}

init(id: Int, name: String) {
self.id = id
self.name = name
}

init(name: String) {
self.name = name
}
}

ToolTableViewController.swift:(使用 XMLHelper.getToolList())

import UIKit

class ToolTableViewController: UITableViewController, XMLParserDelegate {

var tools: [Tool] = []
var eName: String = String()
var toolId = String()
var toolName = String()

override func viewDidLoad() {
super.viewDidLoad()

tableView.tableFooterView = UIView() // to remove empty cells in the list
}

override func viewWillAppear(_ animated: Bool) {
tools = XMLHelper.getToolList()!

// this code piece is working, but i want to outsource it, so i can use it again
/*
let url = "{myUrl}" // not public for security reason
let myURL = URL(string: url)
let parser = XMLParser(contentsOf: myURL!)!
parser.delegate = self as XMLParserDelegate
parser.parse()
*/

tableView.reloadData()*/

print("view did refresh")
}


override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tools.count
}


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)

let cellIdentifier = "ToolTableViewCell" // simple TableViewCell with a label

guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? ToolTableViewCell else {
fatalError("The dequeued cell is not an instance of ToolTableViewCell.")
}

let tool = tools[indexPath.row]

cell.labelName.text = String(tool.id)+" "+tool.name

return cell
}

// MARK: XMLParserDelegate (this code here is only used when the code above is uncommented, it is the same as the code in ToolXMLParserDelegate)

func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
eName = elementName
if elementName == "row" {
toolId = String()
toolName = String()
}
}

func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
if elementName == "row" {

let tool = Tool()
tool.id = Int(toolId)!
tool.name = toolName

tools.append(tool)
}
}

func parser(_ parser: XMLParser, foundCharacters string: String) {
let data = string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)

if (!data.isEmpty) {
if eName == "id" {
toolId += data
} else if eName == "name" {
toolName += data
}
}
}
}

最佳答案

我现在可以使用了,看起来我搞乱了引用资料。

这是我所做的更改:

ToolXMLParserDelegate

init(toolList : [Tool]) { //removed inout
self.tools = toolList
}

XMLHelper

class func getToolList() -> [Tool]? {
// not needed anymore
//var toolList: [Tool] = []

let baseURL = "https://henkel.simonus.de/approval/xml/"
let toolListString = "getToolList.php"

let url = baseURL+toolListString

guard let myURL = URL(string: url) else {
print("URL not defined properly")
return nil
}
guard let parser = XMLParser(contentsOf: myURL as URL) else {
print("Cannot Read Data")
return nil
}

// CHANGES
let myDelegate = ToolXMLParserDelegate(toolList: []) // pass an empty array
parser.delegate = myDelegate

if !parser.parse() {
print("Data Errors Exist:")
let error = parser.parserError!
print("Error Description:\(error.localizedDescription)")
//print("Error reason:\(error.localizedFailureReason)")
print("Line number: \(parser.lineNumber)")
}

// return the list of the delegate instead of the xmlhelpers toolList
return myDelegate.tools
}

关于将方法外包给静态方法时出现 Swift 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45354855/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com