In languages like C++
and C#
when you create a contain such as a std::vector
or a C#
list
you explicitly declare the container type when you create it:
C++:
std::vector<MyObject>
C#:
List<MyObject> list = new List<MyObject>();
Looking at the code above, I know immediately that these containers can only contain objects of type MyObject
and the compiler will complain if I try to add an object that isn't off this type.
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):
Objective-C:
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]];
Instead something like an NSDictionary
or NSArray
will store and accept objects of any type that inherits from NSObject
. 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 runtime
whereas with c++
or c#
I know this at compile time
and just by looking at the code.
Should I be validating the contents of the containers when adding, using and removing objects for container classes (NSArray
, NSSet
, NSDictionary
, etc) from Apple's Foundation Framework? Or is this okay in all circumstances and will verification hurt performance much?:
NSDictionary *dict = [[NSDictionary alloc]init];
[dict objectForKey:@"someKey"]; // return nil?