Nick Nick - 1 month ago 6x
Objective-C Question

How can I access parsed XML data and use it in other methods?

I have an XML file with a comment that has an ID on the bottom of my file that I am successfully NSLog"ing" out to the console. I used a NSXMLParser to find the comment via the foundComment method. I then have a GetUID method at the bottom that I want to return my uid string. I am not sure how to access my parsed data and use it in another separate method. Any help would be greatly appreciated.


<!--7934fad5a3a -->


#import <Foundation/Foundation.h>

@interface MyXmlParserDelegate : NSObject <NSXMLParserDelegate>


#import "XMLParser.h"

@implementation MyXmlParserDelegate

- (void) parserDidStartDocument:(NSXMLParser *)parser {


- (void)parser:(NSXMLParser *)parser
foundComment:(NSString *)uid{

NSLog(@"UID: %@", uid);


- (void) parserDidEndDocument:(NSXMLParser *)parser {



-(NSString *)GetUID {

NSString * uid = nil;

NSXMLParser *parser = [[NSXMLParser alloc] initWithData:MyData];

MyXmlParserDelegate *parserDelegate = [[MyXmlParserDelegate alloc] init];
[parser setDelegate:parserDelegate];

[parser parse];

return uid;



The best answer depends on how reusable you need the parser delegate to be.

If the MAIN object is the only customer, then you can eliminate the delegate class altogether, just make self the delegate where you allocate the parser in GetUID.

A more general idea is keep your delegate class, and think of it specifically as a "uid finder". In this form, it would contain a public uid property which it would initialize during the parse. e.g.

// in the delegate
- (void)parser:(NSXMLParser *)parser foundComment:(NSString *)uid {
    NSLog(@"UID: %@", uid);
    self.uid = uid;

// in the customer
MyXmlParserDelegate *parserDelegate = [[MyXmlParserDelegate alloc] init];
parser.delegate = parserDelegate;
[parser parse];


return parserDelegate.uid;

We could get more general still, but the right approach will depend more on the nature of your model and degree to which the XML parsing process needs generalization.

Side notes: It's customary to name classes and source files the same, so the MyXmlParserDelegate implementation file is better named "MyXmlParserDelegate.m". Also, unless your implementations contain C++, they should have the ".m" extensions.