gpt4 book ai didi

ios - NSXMLParser 问题

转载 作者:行者123 更新时间:2023-11-28 17:40:42 24 4
gpt4 key购买 nike

我使用了一个示例来让 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 代码。相反,我会让 View Controller 成为一个实例变量,并在您初始化解析器时设置它。

MyParser *parser = [[MyParser alloc] init]; 
[parser setViewController:self];

另一种方法是让您的 ViewController 成为 MyParser 的委托(delegate)。在 MyParser.h 中,您可以声明一些委托(delegate)方法:

@protocol MyParserDelegate
- (void)foundBooks:(NSMutableArray *)booksArray;
- (void)foundBook:(Book *)aBook;
@end

@interface MyParser {
id<MyParserDelegate> delegate;
NSMutableArray *bookArray;
Book *aBook;
...
}
@end

然后,您的 View Controller 将是一个委托(delegate):

@interface ViewController : UIViewController <MyParserDelegate> { 

...
}
@end

在 ViewController.m 中,您将实现 foundBooks: 和 foundBook:。

然后,在您的解析器中您将调用委托(delegate)方法:

if([elementName isEqualToString:@"Books"]) {
[self.delegate foundBooks:bookArray];
...
}

if([elementName isEqualToString:@"Book"]) {
[self.delegate foundBook:aBook];
...
}

关于ios - NSXMLParser 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8249873/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com