我正在尝试为 wordpress 博客编写和 RSS 阅读器。我的新闻元素类如下所示:
@property (nonatomic, retain) NSString *title;
@property (nonatomic, retain) NSString *description;
@property (nonatomic, retain) NSString *link;
@property (nonatomic, retain) NSString *pubDate;
我想创建 NewsElements 和 NSMutableArray。XMLParser 类如下所示:
XMLParser.h
@class NewsElement;
@interface XMLParser : NSObject
{
BOOL storingCharacters;
}
@property (nonatomic, retain) NewsElement *newsElement;
@property (nonatomic, retain) NSMutableArray *newsFeed;
@property (nonatomic, retain) NSMutableString *currentElementValue;
-(XMLParser*) initXMLParser;
@end
XMLParser.m
#import "XMLParser.h"
#import "NewsElement.h"
@implementation XMLParser
@synthesize newsElement, newsFeed, currentElementValue;
-(XMLParser*)initXMLParser{
newsFeed = [[NSMutableArray alloc] init];
return self;
}
-(void)parser:(NSXMLParser*)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
if([elementName isEqualToString:@"item"])
{
newsElement = [[NewsElement alloc] init];
}
else if ([elementName isEqualToString:@"title"] || [elementName isEqualToString:@"description"] || [elementName isEqualToString:@"link"] || [elementName isEqualToString:@"pubDate"])
{
[currentElementValue setString:@""];
storingCharacters = YES;
}
}
-(void)parser:(NSXMLParser*)parser foundCharacters:(NSString *)string{
if(storingCharacters)
[currentElementValue appendString:string];
}
-(void)parser:(NSXMLParser*)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if([elementName isEqualToString:@"item"])
{
if([newsFeed description] != nil)
{
[newsFeed addObject:newsElement];
}
}
else if ([elementName isEqualToString:@"title"] || [elementName isEqualToString:@"description"] || [elementName isEqualToString:@"link"] || [elementName isEqualToString:@"pubDate"])
{
[newsElement setValue:currentElementValue forKey:elementName];
storingCharacters = NO;
}
}
@end
当解析器完成时,我有一个包含 5 个元素的数组 - 但所有的值(标题、描述等)都是 nil ......使用调试器我可以看到我确实用真实数据设置了值。
我错过了什么?