Reputation: 1
I am using NSXMLParser to parse a xml file on my desktop. The NSXMLParser object gives exc bad access error when calling parse method.
This is the code
let xmlURl = NSHomeDirectory()+"/Desktop/questions.xml"
let myUrl = NSURL(fileURLWithPath:xmlURl)
let myparser = NSXMLParser(contentsOfURL: myUrl)
myparser?.delegate = MyXMLDelegate()
myparser?.parse() // HERE the EXC bad access code 1
This is the content of the xml file
<?xml version="1.0" encoding="UTF-8"?>
<addresses owner=”swilson”>
<person>
<lastName>Doe</lastName>
<firstName>John</firstName>
<phone location="mobile">(201) 345-6789</phone>
<email>[email protected]</email>
<address>
<street>100 Main Street</street>
<city>Somewhere</city>
<state>New Jersey</state>
<zip>07670</zip>
</address>
</person>
What is the problem of the above code?
Thank you in advance.
Upvotes: 0
Views: 85
Reputation: 11
This is an annoying, un-obvious bug I ran into. The problem is this line:
myparser?.delegate = MyXMLDelegate()
The delegate property is defined as un-owned. So essentially Swift is releasing your delegate right after this line, resulting in a bad access.
To fix keep a reference to your delegate
let delegate = MyXMLDelegate()
myparser?.delegate = delegate
Upvotes: 1