0

要向服务器发送请求以下载数据,我正在使用 NSOperation。接收数据后,我正在使用 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 是实现 Parser 委托方法的 NSObject 的子类,但我的光标没有到达 NSLog。当在 Parser 委托方法中放置调试点时,发现这些方法没有被调用。

谁能告诉我问题出在哪里以及我如何解决这个问题。

提前致谢!

4

1 回答 1

1

I solved above problem by creating subclass of NSOperation and performed parsing in main method of subclass of NSOperation as follows:

//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];
于 2012-07-24T10:45:49.320 回答