OO Objective-C design with XML parsing

Posted by brainfsck on Stack Overflow See other posts from Stack Overflow or by brainfsck
Published on 2009-08-15T21:57:41Z Indexed on 2010/06/01 6:13 UTC
Read the original article Hit count: 271

Hi,

I need to parse an XML record that represents a QuizQuestion. The "type" attribute tells the type of question. I then need to create an appropriate subclass of QuizQuestion based on the question type. The following code works ([auto]release statements omitted for clarity):

QuizQuestion *question = [[QuizQuestion alloc] initWithXMLString:xml];
if( [ [question type] isEqualToString:@"multipleChoiceQuestion"] ) {
    [myQuestions addObject:[[MultipleChoiceQuizQuestion alloc] initWithXMLString:xml];
}

//QuizQuestion.m
-(id)initWithXMLString:(NSString*)xml {
    self.type = ...// parse "type" attribute from xml
    // parse the rest of the xml
}

//MultipleChoiceQuizQuestion.m
-(id)initWithXMLString:(NSString*)xml {
    if( self= [super initWithXMLString:xml] ) {
        // multiple-choice stuff
    }
}

Of course, this means that the XML is parsed twice: once to find out the type of QuizQuestion, and once when the appropriate QuizQuestion is initialized.

To prevent parsing the XML twice, I tried the following approach:

// MultipleChoiceQuizQuestion.m
-(id)initWithQuizRecord:(QuizQuestion*)record {
    self=record; // record has already parsed the "type" and other parameters
    // multiple-choice stuff
}

However, this fails due to the "self=record" assignment; whenever the MultipleChoiceQuizQuestion tries to call an instance-method, it tries to call the method on the QuizQuestion class instead.

Can someone tell me the correct approach for parsing XML into the appropriate subclass when the parent class needs to be initialized to know which subclass is appropriate?

© Stack Overflow or respective owner

Related posts about iphone

Related posts about objective-c