title: Objective-C class type mismatch after cast
body: <p>After parsing the JSON response from a webservice using <code>NSJSONSerialization</code>, I use <code>+isKindOfClass:</code> to make sure the server returned the kind of data I expect. Using this method, I ran into some weird behaviour, which I'll illustrate using an example.</p>
  
  <p>Consider the following objects:</p>
  
  <pre><code>// Definitions
  NSDictionary *son = @{ @"firstname" : @"James", @"lastname" : @"Appleseed" };
  NSDictionary *daughter = @{ @"firstname" : @"Susan", @"lastname" : @"Appleseed"};
  NSArray *children = @[son, daughter];
  NSDictionary *father = @{ @"firstname" : @"John", @"lastname" : @"Appleseed" };
  NSDictionary *family = @{@"children" : children, @"father" : father};
  NSDictionary *pedigree = @{@"family" : family };
  </code></pre>
  
  <p>Those objects represent deserialized JSON returned from a server. Now if I want to use the array of children to calculate how much children there are using NSArray's <code>-count</code>, I need to make sure the children object is an NSArray. If the children object for example happens to be a string, while the app expects an array, it'll crash because strings don't implement a <code>count</code> method. Consider the following code sequence which implements the described check:</p>
  
  <pre><code>// First test
  id _family = [pedigree objectForKey:@"family"];
  if ([_family isKindOfClass:[NSDictionary class]])
  {
      NSDictionary *_family = (NSDictionary *)_family;
      id _children = [_family objectForKey:@"children"];
  
      NSLog(@"Children: %@", _children);
      NSLog(@"Children classname: %@", NSStringFromClass(children.class));
  
      if ([_children isKindOfClass:[NSArray class]]) {
          NSLog(@"Children is an NSArray");
      } else {
          NSLog(@"Children is not an NSArray");
      }
  } else {
      NSLog(@"Family is not an NSDictionary");
  }
  </code></pre>
  
  <p>After running this code, the console outputs the following:</p>
  
  <pre><code>Children: (null)
  Children classname: __NSArrayI
  Children is not an NSArray
  </code></pre>
  
  <p>The console output appears to be extremely remarkable and even contradictory. How could children <em>not</em> be an NSArray while its classname is __NSArrayI?</p>
  
  <p>After a bit of debugging, I found that there are two ways to solve this problem:</p>
  
  <ol>
  <li>remove this line <code>NSDictionary *_family = (NSDictionary *)_family;</code></li>
  <li>use a different name than <code>_family</code> for the casted variable</li>
  </ol>
  
  <p>How could this behaviour be explained?</p>