title: Passing and calling dynamic blocks in Objective C
body: <p>As part of a unit test framework, I'm writing a function <code>genArray</code> that will generate NSArrays populated by a passed in generator block. So <code>[ObjCheck genArray: genInt]</code> would generate an NSArray of random integers, <code>[ObjCheck genArray: genChar]</code> would generate an NSArray of random characters, etc. In particular, I'm getting compiler errors in my implementation of <code>genArray</code> and <code>genString</code>, a wrapper around <code>[ObjCheck genArray: genChar]</code>.</p>
  
  <p>I believe Objective C can manipulate blocks this dynamically, but I don't have the syntax right.</p>
  
  <p><a href="https://github.com/mcandre/objcheck/blob/master/ObjCheck.m" rel="noreferrer">ObjCheck.m</a></p>
  
  <pre><code>+ (id) genArray: (id) gen {
      NSArray* arr = [NSMutableArray array];
  
      int len = [self genInt] % 100;
  
      int i;
      for (i = 0; i &lt; len; i++) {
          id value = gen();
  
          arr = [arr arrayByAddingObject: value];
      }
  
      return arr;
  }
  
  + (id) genString {
      NSString* s = @"";
  
      char (^g)() = ^() {
          return [ObjCheck genChar];
      };
  
      NSArray* arr = [self genArray: g];
      s = [arr componentsJoinedByString: @""];
  
      return s;
  }
  </code></pre>
  
  <p>When I try to compile, gcc complains that it can't do <code>gen()</code>, because <code>gen</code> is not a function. This makes sense, since <code>gen</code> is indeed not a function but an <code>id</code> which must be cast to a function.</p>
  
  <p>But when I rewrite the signatures to use <code>id^()</code> instead of <code>id</code>, I also get compiler errors. Can Objective C handle arbitrarily typed blocks (genArray needs this), or is that too dynamic?</p>