我的项目中的源代码如下所示。
第一个块返回一个对象,第二个块需要对象作为参数传入
[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 中调用的方法
-(void)start{
[_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);
});
}
}