OK, I'll take a stab at this one.
The first thing that you need to know is that object types in Objective-C are ignored at runtime. If you want, you can use a random type for a variable, property, or ivar and it will make no difference e.g. for a method call.This is due to the dynamic nature of Objective-C; it needs to look up selectors at runtime no matter what the object is typed in the source code. The only bad thing that can happen at runtime is you could get an unimplemented method exception (which might kill your app, but good usage of exception handling can minimize this). So, to the runtime, the types are completely superfluous.
So, why use types at all? Why not just make every object type 'id' and not screw around with this issue? The problem with a totally dynamic language is that you miss out on compile-time warnings. For example, calling a method that's not defined for a particular class. These warnings can often save your skin because unimplemented method exceptions are very difficult to track down if you don't have type information for the compiler to create those warnings. Also, these types really help you to know what type of object to pass to a method call or return value. So your code is much easier to read and self-documenting with the objects needed in each situation.
Which brings us to your question.
If you use the protocol syntax below in your method declarations, you can get compile warnings if the returned object didn't adopt that protocol. If you are more interested in an object being of a particular class type, then you might want to use that. It really depends on the context of what the code is doing. If, from this code snippet, the ViewOrdersAccessor is supposed to have adopted the ViewOrdersService protocol, you may well be more interested in the general protocol type rather than a particular class that adopts it. For example, there may be many other objects that could be returned by viewOrdersService in another context and the protocol is really what's important. You're going to have to make this call in your code.
So, use types to get good compiler warnings, to help you write your code, and to document it for others.
Doug Hill Schematic Labs, Inc.
On Nov 3, 2011, at 4:57 PM, Amourine Tech wrote: Greetings: I came across some old ObjC code:
…
1) ----- - (id <ViewOrdersService>)viewOrdersService { return [[[ViewOrdersAccessor alloc] init] autorelease]; }
…
2) --- - (id <AlertsService>)alertsService { return [[[AlertsSAXAccessor alloc] init] autorelease]; }
…
Why not use:
1) - (ViewOrdersAccessor *) … and
2) - (AlertsSAXAccessor *) ?
Is there an advantage to using id <protocol>? Initially it appears a bit more complicated to work with protocols this versus strong class typing.
Ric.
|