01.02.2014 Views

Objective-C Fundamentals

Objective-C Fundamentals

Objective-C Fundamentals

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Important protocols<br />

159<br />

<br />

<br />

<br />

<br />

<br />

<br />

For some applications, examining the structure of the XML they’re receiving will<br />

change the manner in which the application parses. In this case, you say that the XML<br />

contains an element called Author. An Author is defined by a name, age, and gender,<br />

which are simple strings. An author also has a list of Book elements. A Book is defined<br />

by a title, year, and level, which are all simple strings. This analysis ensures that the<br />

NSXMLParser knows what to do.<br />

Most of the time when you parse XML, you’ll be aware of its structure when writing<br />

your parser class and won’t need to investigate the XML feed’s DTD. An example of<br />

this would be the Twitter XML feed for a timeline. You’ll assume you know the XML<br />

structure for your XML and only implement the parsing functions of the NSXMLParser<br />

delegate to parse the Author XML you already looked at.<br />

PARSING AN AUTHOR WITH NSXMLPARSER DELEGATE<br />

The first step when implementing NSXMLParser is to create a class that contains the<br />

parser object and implement its delegate methods. Let’s create a new View-based<br />

project called Parser_Project and a new NSObject subclass called Parser. The only<br />

instance variables you declare for the Parser class are an NSXMLParser and an<br />

NSMutableString to help with some parsing logic you’ll implement. Make the<br />

Parser.h file look like the following:<br />

#import <br />

@interface Parser : NSObject {<br />

NSXMLParser *parser;<br />

NSMutableString *element;<br />

}<br />

@end<br />

You now need an XML file to parse. You can take the XML in listing 7.10 and place it in<br />

a regular text file. Save the file as Sample.xml, and add it to the project. This gives you<br />

a local XML file to parse.<br />

Now you need to fill in Parser.m, which will contain an init method and the<br />

implementation of the three most common NSXMLParser Delegate methods. Let’s<br />

start with the init method; add the code shown in the following listing into Parser.m.<br />

Listing 7.11<br />

Parser.m initializer<br />

- (id)init {<br />

if ((self == [super init])) {<br />

parser = [[NSXMLParser alloc]<br />

initWithContentsOfURL:<br />

[NSURL fileURLWithPath:[[NSBundle mainBundle]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!