title: Should I verify objects inside Foundation API containers?
body: <p>In languages like <code>C++</code> and <code>C#</code> when you create a contain such as a <code>std::vector</code> or a <code>C#</code> <code>list</code> you explicitly declare the container type when you create it:</p>
  
  <p><strong>C++:</strong></p>
  
  <pre><code>std::vector&lt;MyObject&gt;
  </code></pre>
  
  <p><strong>C#:</strong></p>
  
  <pre><code>List&lt;MyObject&gt; list = new List&lt;MyObject&gt;();
  </code></pre>
  
  <p>Looking at the code above, I know immediately that these containers can only contain objects of type <code>MyObject</code> and the compiler will complain if I try to add an object that isn't off this type.</p>
  
  <p>Since Objective-C is a dynamic language, we don't have the privilege of the compiler warning us about this (because it is a perfectly valid but potentially dangerous thing to do):</p>
  
  <p><strong>Objective-C:</strong></p>
  
  <pre><code>NSDictionary *dict = [[NSDictionary alloc]init];
  [dict setValue:[[SomeClass alloc]init] forKey:@"someClass"];
  [dict setValue:[[NSMutableString alloc]init] forKey:@"mutableString"];
  BOOL classIsSomeClass = [[dict objectForKey:@"someClass"] isKindOfClass:[SomeClass class]];
  </code></pre>
  
  <p>Instead something like an <code>NSDictionary</code> or <code>NSArray</code> will store and accept objects of any type that inherits from <code>NSObject</code>. I find this in itself very flexible but I cannot really be sure of the object type in the container I can only really know at <code>runtime</code> whereas with <code>c++</code> or <code>c#</code> I know this at <code>compile time</code> and just by looking at the code.</p>
  
  <p>Should I be validating the contents of the containers when adding, using and removing objects for container classes (<code>NSArray</code>, <code>NSSet</code>, <code>NSDictionary</code>, etc) from Apple's <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/ObjC_classic/index.html" rel="nofollow noreferrer">Foundation Framework</a>? Or is this okay in all circumstances and will verification hurt performance much?:</p>
  
  <pre><code>NSDictionary *dict = [[NSDictionary alloc]init];
  [dict objectForKey:@"someKey"];    // return nil?
  </code></pre>