简体   繁体   中英

Custom block inside dispatch_async

This code works

[[MyManager sharedManager] makeRequestAndParsingfor:someParameters 
                                            success:^(NSDictionary * dictionary){
                                                // Sucessful response
                                                NSLog(@"Success!!");
                                            } 
                                            failure:^(NSError* error){ 
                                                // Error response
                                                NSLog(@"Failure!");    
                                            }];

But this whenever I run the same in the background it never enters in success or failure block.

dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
    [[MyManager sharedManager] makeRequestAndParsingfor:someParameters 
                                                success:^(NSDictionary * dictionary){
                                                    // Sucessful response
                                                    NSLog(@"Success!!");
                                                } 
                                                failure:^(NSError* error){ 
                                                    // Error response
                                                    NSLog(@"Failure!");    
                                                }];
}];

Can anybody explain me what happens? The method makeRequestAndParsingfor : makes an asynchronous request (with blocks again) and then parses the result. My debugger shows that it never gets in its own success/failure in the second case. In the first case it works like a charm. Any ideas?

Does your method 'makeRequestAndParsingfor' use block_copy() of the args, and store the return in a strong variable (to get the blocks in the heap)? Also add asserts() so you can verify you get both blocks in 'makeRequestAndParsingfor', and even retest before calling one or the other. [In the past use of block_copy() was necessary but now not 100% sure.]

Note that in the second case, where 'makeRequestAndParsingfor' runs in a concurrent queue that multiple of these can call the blocks concurrently - not sure what your success/failure block does, but it better be thread safe, or you should run the block on the main queue in 'makeRequestAndParsingfor' (which I do in my similarly constructed app).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM