这是 NSOperation 的一个子类,我用它来对 NSOperationQueue 进行所有 xml 解析:
#import <Foundation/Foundation.h>
#import "GDBaseParser.h"
@class ParseXMLOperation;
@protocol ParseXMLCallbackDelegate <NSObject>
-(void)parseOperationComplete:(ParseXMLOperation *)completedOperation;
@end
@interface ParseXMLOperation : NSOperation
{
GDBaseParser *xmlParserDelegate;
NSData *dataToParse;
id <ParseXMLCallbackDelegate> callbackDelegate;
}
@property(nonatomic,strong)GDBaseParser *xmlParserDelegate;
@property(nonatomic,strong)NSData *dataToParse;
@property(nonatomic,strong)id <ParseXMLCallbackDelegate> callbackDelegate;
-(id)initWithParser:(GDBaseParser *)inParserDelegate;
@end
@implementation ParseXMLOperation
@synthesize xmlParserDelegate, dataToParse, callbackDelegate;
-(id)initWithParser:(GDBaseParser *)inParserDelegate
{
self = [super init];
if( self != nil )
{
self.xmlParserDelegate = inParserDelegate;
}
return self;
}
-(void)main
{
@autoreleasepool
{
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:dataToParse];
xmlParserDelegate.currentContext = localContext;
[parser setDelegate:xmlParserDelegate];
[parser setShouldProcessNamespaces:NO];
[parser setShouldReportNamespacePrefixes:NO];
[parser setShouldResolveExternalEntities:NO];
[parser parse];
[self performSelectorOnMainThread:@selector(sendOperationComplete) withObject:nil waitUntilDone:NO];
}
}
-(void)sendOperationComplete
{
if( callbackDelegate != nil && [callbackDelegate respondsToSelector:@selector(parseOperationComplete:)] )
{
[callbackDelegate parseOperationComplete:self];
}
}
然后我可以设置操作并将其添加到队列中:
MyParser *parserDelegate = [[MyParser alloc] init];
ParseXMLOperation *parseOperation = [[ParseXMLOperation alloc] initWithParser:parserDelegate];
parseOperation.dataToParse = parseData;
parseOperation.completionBlock = ^{
localOperation.messageHeaderDict = parserDelegate.messageHeaders;
dispatch_async(dispatch_get_main_queue(), ^{
//notify your UI that you are done with your parsing
});
};
[self.xmlParsingQueue addOperation:parseOperation];