Say I have two classes:
@interface Rectangle: NSObject {
int width;
int height;
}
// Methods here...
@end
@interface Square: Rectangle
- (void)initWithLength:(int) length;
@end
Square inherits from Rectangle. Now, if I have a method that takes a Rectangle in another class, say, - (void)drawShape:(Rectangle *) rectangle, can I pass a Square object to it? Should I be using id? What is the best way to dynamically type inherited classes?
Also: This is just an example. My classes are much more complicated than this. For instance, categories would not apply for my actual problem. And if I were using an abstract class above Rectangle, Shape for example, would that change the answer?
If you have a known base class then you should use that. id is useful if you are doing duck typing, but compile time checking is always a good measure against bugs.
id is generally used in concert with protocols. Let’s say you have one called MyProtocol. Then you could type a var as id < MyProtocol >. This will allow the compiler to statically verify your code.