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?
This was released in Xcode 7 (finally!)
Note that in Objective C code, it's just a compile-time check; there will be no run-time error just for putting the wrong type into a collection or assigning to a typed property.
Declare:
Use:
Be careful about those
*
s.Take a look at:
https://github.com/tomersh/Objective-C-Generics
It appears to be a sort of poor-man's generics, by repurposing the protocol checking mechanism.
Generic NSArrays can be realized by subclassing
NSArray
, and redefining all provided methods with more restrictive ones. For example,would have to be redefined in
as
for an NSArray to contain only NSStrings.
The created subclass can be used as a drop-in replacement and brings many useful features: compiler warnings, property access, better code creation and -completion in Xcode. All these are compile-time features, there is no need to redefine the actual implementation - NSArray's methods can still be used.
It's possible to automate this and boil it down to only two statements, which brings it close to languages that support generics. I've created an automation with WMGenericCollection, where templates are provided as C Preprocessor Macros.
After importing the header file containing the macro, you can create a generic NSArray with two statements: one for the interface and one for the implementation. You only need to provide the data type you want to store and names for your subclasses. WMGenericCollection provides such templates for
NSArray
,NSDictionary
andNSSet
, as well as their mutable counterparts.An example:
List<int>
could be realized by a custom class calledNumberArray
, which is created with the following statement:Once you've created
NumberArray
, you can use it everywhere in your project. It lacks the syntax of<int>
, but you can choose your own naming scheme to label these as classes as templates.Just want to jump in here. I've written a blog post over here about Generics.
The thing I want to contribute is that Generics can be added to any class, not just the collection classes as Apple indicates.
I've successfully added then to a variety of classes as they work exactly the same as Apple's collections do. ie. compile time checking, code completion, enabling the removal of casts, etc.
Enjoy.
Now dreams come true - there are Generics in Objective-C since today (thanks, WWDC). It's not a joke - on official page of Swift:
And image that proofs this: