RSS阅读使用NSXMLParser无法正常工作

时间:2012-09-09 04:27:57

标签: iphone xml xcode rss nsxmlparser

我正在尝试为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 ...使用调试器我可以看到我用实际数据设置值

我错过了什么?

1 个答案:

答案 0 :(得分:1)

您需要实例化NSMutableString,而您正在调用appendString:

-(XMLParser*)initXMLParser{
    self = [super init];
    if (self){
        newsFeed = [[NSMutableArray alloc] init];
        currentElementValue = [[NSMutableString alloc] init];
    }
    return self;
}