views:

2055

answers:

3

I'm new to Mac/iPhone programming and Objective-C. In C# and Java we have "generics", collection classes whose members can only be of the type declared. For example, in C#

Dictionary<int, MyCustomObject>

can only contain keys that are integers and values that are of type MyCustomObject. Does a similar mechanism exist in Objective-C?

+4  A: 

There are no generics in Objective-C.

From the Docs

Arrays are ordered collections of objects. Cocoa provides several array classes, NSArray, NSMutableArray (a subclass of NSArray), and NSPointerArray.

Matthew Vines
+26  A: 

No, there are no generics in Objective-C unless you want to use C++ templates in your own custom collection classes (which I strongly discourage). Objective-C is a dynamically typed language, which means that the runtime doesn't care about the type of an objects since all objects can receive messages. When you add an object to a built-in collection, they are just treated as if they were type id. But don't worry, just send messages to those objects like normal; it will work fine. Generics are needed in languages such as Java and C# because they are strong, statically typed languages. Totally different ballgame than Objective-C.

Marc W
+9  A: 

You may be interested in answers to this question: Is there any way to enforce typing on NSArray, NSMutableArray, etc.?.

Arguments are given why it is not common practice in Objective-C/Cocoa.

mouviciel