It sounds as though you need duck-typing, which is supported in Objective-C in the following ways:
- Use a protocol - this works the same as an interface in C#. The base protocl is id<NSObject> (or less correctly, just 'id')
- Use an abstract base class (A special case of this in Objective-C is the class cluster).
- Use categories to mix-in interface conformance on a class.
- Two objects deriving from completely different base classes / protocols that respond to the same method signature can happily be cast to each other in order to invoke that method.
- Use performSelector, NSInvocation or objc_msgSend to invoke a method, if you know the object will happily respond to it.
Common Approach:
For very loosely defined protocols, approach number four is common: We declare a method as follows:
- (void)saveToInventory:(id)inventoryItem
{
if ([inventoryItem respondsToSelector:@selector(sendToWarehouse])
{
id<Warehouseable> warehouseable = (id<Warehouseable>) inventoryItem;
[warehouseable sendToWarehouse];
}
}
. . . while this approach works, it doesn't have a great deal of rigor. Its better to define a stricter protocol.
Rigorous Approach: Replace 'isKindOfClass/respondsToSelector' with polymorphism:
In general its good practice to replace 'isKindOfClass' with polymorphism. Rather than check for a given type, define an interface contract and let a given instance handle this as required. This leads to cleaner, more maintainable code.
In objective-C, the dynamic method dispatch system, makes mix-ins very easy where in C# or Java they require sophisticated libraries. Therefore, even classes that come from a 3rd party, and for which you don't have the source can be extended to all conform to a given protocol. Just define a category method on each class to perform the work. Be sure to use a method name that won't lead to a namespace collision. Example:
@protocol Themeable
-(void)setTheme:(Theme*)theme
@end
UITextField(ThemeAdditions)<MyAppThemeable>
- (void)setTheme:(Theme*)theme
{
//Now your text field can respond to this interface
}
Generics in Objective-C:
You mentioned generic-types in your example above. Its not clear how this fits in. In any case its not explicitly supported in Objective-C, although it can be retro-fitted with some caveats. Here's a library that does this: https://github.com/tomersh/Objective-C-Generics
Note that even without generics, its generally not necessary to explicitly cast in Objective-C: NSArray, NSSet, etc all use id as the type being stored. . . this of course doesn't give you compile-time checking. We generally live without this, although if its badly needed something like the library above could help.