我需要解析表示QuizQuestion的XML记录。" type“属性告诉问题的类型。然后,我需要根据问题类型创建一个适当的QuizQuestion子类。以下代码可以工作(为清楚起见,省略了自动释放语句):
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
}
}当然,这意味着要对XML进行两次解析:一次是为了找出QuizQuestion的类型,另一次是在初始化适当的QuizQuestion时。
为了避免两次解析XML,我尝试了以下方法:
// MultipleChoiceQuizQuestion.m
-(id)initWithQuizRecord:(QuizQuestion*)record {
self=record; // record has already parsed the "type" and other parameters
// multiple-choice stuff
}但是,由于"self=record“赋值导致此操作失败;每当MultipleChoiceQuizQuestion尝试调用实例方法时,它都会尝试调用QuizQuestion类上的方法。
有人能告诉我,当父类需要初始化才能知道哪个子类是合适的时,正确的方法是将XML解析成合适的子类吗?
发布于 2009-08-15 22:06:08
我假设您正在使用NSXMLParser来解析XML字符串,并使用它触发的一些事件来解析XML源。在MultipleChoiceQuizQuestion中,您可以覆盖NSXMLParser的委托方法,例如:
- (void)parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
[super parser:parser
didStartElement:elementName
namespaceURI:namespaceURI
qualifiedName:qName attributes:attributeDict]
// Multiple-choice specific stuff goes here.
}然后按照建议调用self = [super initWithXMLString:xml]。
发布于 2009-08-15 22:08:07
如果你想在init中返回一个不同的实例,你需要这样做:
-(id)init {
if (iNeedToBeADifferentClass) {
[self release];
return [[MyOtherClass alloc] init];
} else {
if (self = [super init]) {
// normal init stuff
}
return self;
}
}使用这种方法,您可以在QuizQuestion中解析XML,用解析的值初始化MultipleChoiceQuizQuestion以及只有MultipleChoiceQuizQuestion需要解析的额外的XML块。
否则,您可以使用工厂类或其他模式。这完全取决于您的XML的结构,尽管- if您的XML的结构考虑到了解析,但在代码中做这件事要容易得多。
https://stackoverflow.com/questions/1282965
复制相似问题