« Guess What I'm doing? | Main | They do share a first name »

cocoa xml parsing

Once you get the hang of it, the NSXmlParser isn't too hard. It's event based. This means that you have to think about your code in terms of each XML open and close tag as being an event that's triggered as your parser reads through the file from top to bottom.

My Nike+ cocoa XML parser and data model is working now. I still have some tweaks and additions to do and then I'll wrap it up in a framework and release it, probably under LGPL.

If you want to see it... this is the place to be.

I added a useful method to NSNumber today as well. If you're not new to objc like I am, feel free to pimp my code. It's below. :)

//
//  NSNumberAdditions.h
//  ipodTest1
//
//  Created by Jonathan Saggau on 8/31/06.
//  Copyright 2006 __MyCompanyName__. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface NSNumber (NSNumberAdditions)

+ (NSNumber *)numberWithString:(NSString *)string;
// pass in a string representing a number...
@end

//
// NSNumberAdditions.m
// ipodTest1
//
// Created by Jonathan Saggau on 8/31/06.
// Copyright 2006 __MyCompanyName__. All rights reserved.
//

#import "NSNumberAdditions.h"

@implementation NSNumber (NSNumberAdditions)

+ (NSNumber *)numberWithString:(NSString *)string;
{
NSScanner *scanner;
int scanLocation = 0;

scanner = [NSScanner scannerWithString:string];
if ([string hasPrefix:@"$"]) scanLocation = 1;
// just in case we're given a dollar value

int intResult;
[scanner setScanLocation:scanLocation];
if ([scanner scanInt:&intResult]
&& ([scanner scanLocation] == [string length] )) {
return [NSNumber numberWithInt:intResult];
}

float floatResult;
[scanner setScanLocation:scanLocation];
if ([scanner scanFloat:&floatResult]
&& ([scanner scanLocation] == [string length] )) {
return [NSNumber numberWithFloat:floatResult];
}

long long longLongResult;
[scanner setScanLocation:scanLocation];
if ([scanner scanLongLong:&longLongResult]
&& ([scanner scanLocation] == [string length] )) {
return [NSNumber numberWithLongLong:floatResult];
}

NSLog(@"WARNING::: Couldn't convert %@ to nsnumber", string);
return [NSNumber numberWithInt:0];
}
@end

TrackBack

TrackBack URL for this entry:
http://www.jonathansaggau.com/blog/mt-tb.cgi/63

Post a comment

(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)