2

I am trying to create objects dynamically based on the output of an XML file. My apologies if there are other posts on this subject, I don't even know what this is called. Basically I want to create a stack of objects that could be of any class. In a nutshell, when the "didStartElement" of the NSXMLParser is called, I want to create an object of type "elementName" and stack it to my object stack. The code below is not working, just trying to illustrate what I am trying to accomplish. Normally I would just put "objectStack.append(object) as object" but in this case I don't know what the object type is going to be until the element is scanned by the XML parser. I believe the NSClassFromString is the way to do this, but it's not working.

func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {

    objectStack.append(NSClassFromString(elementName))

}

Any assistance would be greatly appreciated. Even if you can just point me in the right direction.

2
  • When you say its not working? Whats the error you are getting? I think you need to actually alloc & init the object, try objectStack.append(NSClassFromString(elementName)()) note the extra (). Commented Jul 22, 2016 at 21:50
  • 1
    Just solved the issue, I was really close. I just need to prepend the project name in front of the element name. Working code to follow. Commented Jul 22, 2016 at 21:55

1 Answer 1

1

Got it working, the problem was that I needed the fully qualified name of the class, with the project name.

Working code:

var objectStack = [AnyClass]()
func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {

    var className = String(NSString(format: "MyProject.%@", elementName))
    objectStack.append(NSClassFromString(className)!)
}
Sign up to request clarification or add additional context in comments.

2 Comments

Does this work for NSObject, AnyObject, Any, struct, and/or type aliases.
To be honest I haven't tried. I only used this on NSObject. My code has changed again to init the object. I can post the updated code if you would like.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.