如何将一个方法用两个块作为参数,第一个块有一个返回值,第二个块需要得到返回值

时间:2013-03-06 05:47:39

标签: html-parsing block exc-bad-access grand-central-dispatch

我项目中的源代码如下。

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); 


        });
    }

}

0 个答案:

没有答案