Search code examples
iosobjective-cxml-parsingdelegatestree-structure

How to change the delegate to be an instance of an object


I'm new to ObjectiveC and am trying to parse an XML file as described in this article:

https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/XMLParsing/Articles/ConstructingTrees.html

Trouble is, I don't understand what the article means in step 3 by "The method that creates and initializes the object also sets it to be the new delegate of the NSXMLParser instance."

Does this require adding a method to the MyElement class, or is the code added into the top level object?

Can anyone give a code sample of what they mean here?


Solution

  • You need to set the delegate that will handle the parser functions.

    On your .h file:

    @interface MyParser : NSObject <NSXMLParserDelegate>
    

    On your .m file:

    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:dataToParse];
    [parser setDelegate:self];
    

    That will link your file to the parser and will expect your class to have all the methods to handle the parsing work:

    - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict;
    - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
    - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
    

    Fill the behavior of the methods to actually do the parsing.