NSXMLParser和NSOperation无法正常工作

时间:2012-07-24 09:35:03

标签: iphone objective-c nsxmlparser nsoperation

向服务器发送请求以下载数据我正在使用NSOperation.After接收数据后我使用NSXMLParser来解析响应,但它没有调用解析器委托方法

-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName 

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName

任何人都可以告诉我哪里做错了。

//Creating NSOperation as follows:
NSOperationQueue *operationQueue = [NSOperationQueue new];
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(createRequestToGetData) object:nil]; 
[operationQueue addOperation:operation];
[operation release];    

-(void)createRequestToGetData
{
    NSError *error;
    NSURL *theURL = [NSURL URLWithString:myUrl];
    NSData *data = [NSData dataWithContentsOfURL:theURL];

    MyXMLParser *theXMLParser = [[MyXMLParser alloc]init];
    NSError *theError = NULL;
    [theXMLParser parseXMLFileWithData:data parseError:&theError];
    NSLog(@"Parse data:%@",theXMLParser.mParsedDict); //Cursor is not coming here.
    [theXMLParser release];
}

注意:MyXMLParser是NSObject的子类,它实现了Parser委托方法,但我的光标没有到达NSLog。当在Parser委托方法中放置调试点时发现这些方法没有被调用。

任何人都可以告诉问题在哪里以及如何解决这个问题。

提前致谢!

1 个答案:

答案 0 :(得分:1)

我通过创建NSOperation的子类并在NSOperation的子类的main方法中执行解析来解决上述问题,如下所示:

//DataDownloadOperation.h
#import <Foundation/Foundation.h>

@interface DataDownloadOperation : NSOperation
{
    NSURL *targetURL;
}
@property(retain) NSURL *targetURL;
- (id)initWithURL:(NSURL*)url;

@end


//DataDownloadOperation.m
#import "DataDownloadOperation.h"
#import "MyXMLParser.h"

@implementation DataDownloadOperation
@synthesize targetURL;

- (id)initWithURL:(NSURL*)url
{
    if (![super init]) return nil;
    self.targetURL = url;
    return self;
}

- (void)dealloc {
    [targetURL release], targetURL = nil;
    [super dealloc];
}

- (void)main {

    NSData *data = [NSData dataWithContentsOfURL:self.targetURL];
    MyXMLParser *theXMLParser = [[MyXMLParser alloc]init];
    NSError *theError = NULL;
    [theXMLParser parseXMLFileWithData:data parseError:&theError];
    NSLog(@"Parse data1111:%@",theXMLParser.mParsedDict);
    [theXMLParser release];
}
@end
//Created NSOperation as follows:
NSURL *theURL = [NSURL URLWithString:myurl];
        NSOperationQueue *operationQueue = [NSOperationQueue new];
        DataDownloadOperation *operation = [[DataDownloadOperation alloc] initWithURL:theURL];
         [operationQueue addOperation:operation];
         [operation release];