Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>One way to reduce nesting is to define methods that return the individual blocks. In order to facilitate the data sharing which is done "auto-magically" by the Objective C compiler through closures, you would need to define a separate class to hold the shared state.</p> <p>Here is a rough sketch of how this can be done:</p> <pre><code>typedef void (^WithStatus)(int); @interface AsyncHandler : NSObject { NSString *_sharedString; NSURL *_innerUrl; NSURL *_middleUrl; WithStatus _innermostBlock; } +(void)handleRequest:(WithStatus)innermostBlock outerUrl:(NSURL*)outerUrl middleUrl:(NSURL*)middleUrl innerUrl:(NSURL*)innerUrl; -(WithStatus)outerBlock; -(WithStatus)middleBlock; @end @implementation AsyncHandler +(void)handleRequest:(WithStatus)innermostBlock outerUrl:(NSURL*)outerUrl middleUrl:(NSURL*)middleUrl innerUrl:(NSURL*)innerUrl { AsyncHandler *h = [[AsyncHandler alloc] init]; h-&gt;_innermostBlock = innermostBlock; h-&gt;_innerUrl = innerUrl; h-&gt;_middleUrl = middleUrl; [remoteAPIWithURL:outerUrl success:[self outerBlock]]; } -(WithStatus)outerBlock { return ^(int success) { _sharedString = [NSString stringWithFormat:@"Outer: %i", success]; [remoteAPIWithURL:_middleUrl success:[self middleBlock]]; }; } -(WithStatus)middleBlock { return ^(int success) { NSLog("Shared string: %@", _sharedString); [remoteAPIWithURL:_innerUrl success:_innermostBlock]; }; } @end </code></pre> <p>Note: All of this assumes ARC; if you are compiling without it, you need to use <a href="https://stackoverflow.com/a/2659357/335858"><code>Block_copy</code></a> in the methods returning blocks. You would also need to do a copy in the calling code below.</p> <p>Now your original function can be re-written without the <a href="http://en.wikipedia.org/wiki/Matryoshka_doll" rel="nofollow noreferrer">"Russian doll"</a> nesting, like this:</p> <pre><code>[AsyncHandler handleRequest:^(int status){ //succes!!! } outerUrl:[NSURL @"http://my.first.url.com"] middleUrl:[NSURL @"http://my.second.url.com"] innerUrl:[NSURL @"http://my.third.url.com"] ]; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload