我项目中的源代码如下。
frist块返回一个对象,第二个块需要将对象作为param传入
[kNetManagerInstance exeHttpRequest:anUrl requestFrom:self withParseBlock:^id(NSData *htmlData) {
NSMutableArray *arr = doSomeParsingWorkOn(htmlData);
return arr; //return the html parsed result for the seconde block to use.
} andResultBlock:^(id object) {
NSLog(@"%@",object);//can output the object but
//crash when execute out of the scope,EXC_BAD_ACCESS(code=2,address=0xc)
}];
上面的方法就像下面做的那样。
-(id)init:(NSString *)url
withParseBlock:(htmlParseBlock)parseBlock
andResultBlock:(ItemsReturnBlock)resultBlock
{
self = [super init];
if(self!=nil){
[_parseBlock release];
_parseBlock = [parseBlock copy];
[_returnBlock release];
_returnBlock = [resultBlock copy];
_asiRequest = [[ASIHTTPRequest alloc ] initWithURL:[NSURL URLWithString:url]];
__block HttpParseSession * self_ = self;
dispatch_queue_t httpQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, nil);
dispatch_block_t block = ^{
@autoreleasepool {
[self_ start];
}
};
if(dispatch_get_current_queue()==httpQueue){
block();
}else{
dispatch_async(httpQueue, block);
}
}
return self;
}
在httpQueue中调用的方法
- (无效)开始{
[_asiRequest startSynchronous];
NSData *data = _asiRequest.responseData;
__block id result = _parseBlock(data); //get the parsed result
dispatch_queue_t mainQueue = dispatch_get_main_queue();
if(dispatch_get_current_queue()==mainQueue){
_returnBlock(result);
}else{
dispatch_async(mainQueue, ^{
_returnBlock(result);
});
}
}