У меня сейчас проблема с анализом информации из XML в NSMutableArray, я вставил приведенный ниже код, который для парсера извлекает документ из интернета и создает массив. Затем я пытаюсь скопировать элементы из анализатора xml в NSMutableArray для поиска, но каждый раз, когда я пытаюсь скопировать массив, он возвращает ошибку структуры, поэтому я удалил изменения на данный момент.
Вот код парсера и текущий код для viewdidload в контроллере основного вида, если кто-то может помочь, я был бы очень признателен.
#import "BlogRssParser.h"
#import "BlogRss.h"
@implementation BlogRssParser
@synthesize currentItem = _currentItem;
@synthesize currentItemValue = _currentItemValue;
@synthesize rssItems = _rssItems;
@synthesize delegate = _delegate;
@synthesize retrieverQueue = _retrieverQueue;
- (id)init{
if(![super init]){
return nil;
}
_rssItems = [[NSMutableArray alloc]init];
return self;
}
- (NSOperationQueue *)retrieverQueue {
if(nil == _retrieverQueue) {
_retrieverQueue = [[NSOperationQueue alloc] init];
_retrieverQueue.maxConcurrentOperationCount = 1;
}
return _retrieverQueue;
}
- (void)startProcess{
SEL method = @selector(fetchAndParseRss);
[[self rssItems] removeAllObjects];
NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self
selector:method
object:nil];
[self.retrieverQueue addOperation:op];
[op release];
}
-(BOOL)fetchAndParseRss{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
//To suppress the leak in NSXMLParser
[[NSURLCache sharedURLCache] setMemoryCapacity:0];
[[NSURLCache sharedURLCache] setDiskCapacity:0];
NSURL *url = [NSURL URLWithString:@"http://xxxxxxxxx.co.uk/rssparser/Data.xml"];
BOOL success = NO;
NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:url];
[parser setDelegate:self];
[parser setShouldProcessNamespaces:YES];
[parser setShouldReportNamespacePrefixes:YES];
[parser setShouldResolveExternalEntities:NO];
success = [parser parse];
[parser release];
[pool drain];
return success;
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict{
if(nil != qualifiedName){
elementName = qualifiedName;
}
if ([elementName isEqualToString:@"item"]) {
self.currentItem = [[[BlogRss alloc]init]autorelease];
} else if([elementName isEqualToString:@"title"] ||
[elementName isEqualToString:@"description"] ||
[elementName isEqualToString:@"mediaUrl"] ||
[elementName isEqualToString:@"link"] ||
[elementName isEqualToString:@"guid"] ||
[elementName isEqualToString:@"pubDate"]) {
self.currentItemValue = [NSMutableString string];
} else {
self.currentItemValue = nil;
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if(nil != qName){
elementName = qName;
}
if([elementName isEqualToString:@"title"]){
self.currentItem.title = self.currentItemValue;
}else if([elementName isEqualToString:@"description"]){
self.currentItem.description = self.currentItemValue;
}else if([elementName isEqualToString:@"link"]){
self.currentItem.linkUrl = self.currentItemValue;
}else if([elementName isEqualToString:@"mediaUrl"]){
self.currentItem.mediaUrl = self.currentItemValue;
}else if([elementName isEqualToString:@"guid"]){
self.currentItem.guidUrl = self.currentItemValue;
}else if([elementName isEqualToString:@"pubDate"]){
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
self.currentItem.pubDate = [formatter dateFromString:self.currentItemValue];
[formatter release];
}else if([elementName isEqualToString:@"item"]){
[[self rssItems] addObject:self.currentItem];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if(nil != self.currentItemValue){
[self.currentItemValue appendString:string];
}
}
- (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock{
//Not needed for now
}
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError{
if(parseError.code != NSXMLParserDelegateAbortedParseError) {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[(id)[self delegate] performSelectorOnMainThread:@selector(processHasErrors)
withObject:nil
waitUntilDone:NO];
}
}
- (void)parserDidEndDocument:(NSXMLParser *)parser {
[(id)[self delegate] performSelectorOnMainThread:@selector(processCompleted)
withObject:nil
waitUntilDone:NO];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
-(void)dealloc{
self.currentItem = nil;
self.currentItemValue = nil;
self.delegate = nil;
[_rssItems release];
[super dealloc];
}
@end
BlogRSSParser.h
#import <Foundation/Foundation.h>
@class BlogRss;
@protocol BlogRssParserDelegate;
@interface BlogRssParser : NSObject <NSXMLParserDelegate>{
BlogRss * _currentItem;
NSMutableString * _currentItemValue;
NSMutableArray * _rssItems;
id<BlogRssParserDelegate> _delegate;
NSOperationQueue *_retrieverQueue;
}
@property(nonatomic, retain) BlogRss * currentItem;
@property(nonatomic, retain) NSMutableString * currentItemValue;
@property(readonly) NSMutableArray * rssItems;
@property(nonatomic, assign) id<BlogRssParserDelegate> delegate;
@property(nonatomic, retain) NSOperationQueue *retrieverQueue;
- (void)startProcess;
@end
@protocol BlogRssParserDelegate <NSObject>
-(void)processCompleted;
-(void)processHasErrors;
@end
ViewDidLoad
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
[self toolbarInit];
_rssParser = [[BlogRssParser alloc]init];
self.rssParser.delegate = self;
[[self rssParser]startProcess];
}