Ios NSXMLParser故障
我使用了一个示例来了解Ios NSXMLParser故障,ios,nsxmlparser,Ios,Nsxmlparser,我使用了一个示例来了解NSXMLParser,但我不需要将其用于appDelegate,而是用于其他ViewController,这似乎不起作用: @implementation XMLParser - (XMLParser *) initXMLParser { [super init]; viewController = (ViewController *)[[UIApplication sharedApplication] delegate]; return
NSXMLParser
,但我不需要将其用于appDelegate
,而是用于其他ViewController,这似乎不起作用:
@implementation XMLParser
- (XMLParser *) initXMLParser {
[super init];
viewController = (ViewController *)[[UIApplication sharedApplication] delegate];
return self;
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict {
if([elementName isEqualToString:@"Books"]) {
//Initialize the array.
viewController.books = [[NSMutableArray alloc] init];
}
else if([elementName isEqualToString:@"Book"]) {
//Initialize the book.
aBook = [[Book alloc] init];
//Extract the attribute here.
aBook.bookID = [[attributeDict objectForKey:@"id"] integerValue];
NSLog(@"Reading id value :%i", aBook.bookID);
}
NSLog(@"Processing Element: %@", elementName);
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if(!currentElementValue)
currentElementValue = [[NSMutableString alloc] initWithString:string];
else
[currentElementValue appendString:string];
NSLog(@"Processing Value: %@", currentElementValue);
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if([elementName isEqualToString:@"Books"])
return;
//There is nothing to do if we encounter the Books element here.
//If we encounter the Book element howevere, we want to add the book object to the array
// and release the object.
if([elementName isEqualToString:@"Book"]) {
[viewController.books addObject:aBook];
[aBook release];
aBook = nil;
}
else
[aBook setValue:currentElementValue forKey:elementName];
[currentElementValue release];
currentElementValue = nil;
}
解析后,
viewController.books
中没有任何对象。为什么?我可能会去掉initXMLParser代码。相反,我会将视图控制器设置为实例变量,并在初始化解析器时进行设置
MyParser *parser = [[MyParser alloc] init];
[parser setViewController:self];
另一种方法是使ViewController成为MyParser的委托。在MyParser.h中,可以声明一些委托方法:
@protocol MyParserDelegate
- (void)foundBooks:(NSMutableArray *)booksArray;
- (void)foundBook:(Book *)aBook;
@end
@interface MyParser {
id<MyParserDelegate> delegate;
NSMutableArray *bookArray;
Book *aBook;
...
}
@end
if([elementName isEqualToString:@"Books"]) {
[self.delegate foundBooks:bookArray];
...
}
if([elementName isEqualToString:@"Book"]) {
[self.delegate foundBook:aBook];
...
}
您正在将AppDelegate键入您正在调用的对象
ViewController
-看起来很可疑。
if([elementName isEqualToString:@"Books"]) {
[self.delegate foundBooks:bookArray];
...
}
if([elementName isEqualToString:@"Book"]) {
[self.delegate foundBook:aBook];
...
}