Why does factory return a generic object of an unspecified type?
In many cases, when you see the returned id , this is because they were not printed sequentially (really abstract objects), or because an implicit upcast was introduced.
Is this a bug (which allows the factory to return something else that is not a button), or is there any reason for this?
It's not a mistake. Of course, you should not return a type that does not match.
I would write a factory as follows: ... am I mistaken?
@implementation WinFactory - (id<Button>)createButton { return [[[WinButton alloc] init] autorelease]; } @end
The big mistake in this scenario is that ObjC is pretty weakly typed, and you should strive to ensure that all selector parameters and return types are consistent . That is, each createButton in all your translations must return the same type and have the same parameter types. Sometimes you need to choose a more descriptive name to avoid ambiguity for the compiler.
This should explain why +[NSString string] returns id - if it returned NSString , then +[NSMutableString string] could be a source of warnings. This is due to the fact that the compiler may have a difficult (impossible) time corresponding to the declaration of the method to a dynamic instance. It can also help you understand the βverboseβ designation of selectors, for example convenience constructors that also contain a method type (for example, +[NSDictionary dictionaryWithObject:] , and not just +[NSDictionary withObject:] ).
But to answer your question: id<Button> or NSObject<Button>* or some other qualified type - this is normal - as long as you can live with this common method signature. You introduce a type qualification that helps the compiler help you.
source share