0

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

我错过了什么?

4

1 回答 1

1

你需要实例化你的NSMutableString,你调用appendString:的是零。

-(XMLParser*)initXMLParser{
    self = [super init];
    if (self){
        newsFeed = [[NSMutableArray alloc] init];
        currentElementValue = [[NSMutableString alloc] init];
    }
    return self;
}
于 2012-09-09T04:51:35.413 回答