Show Your id
Sometimes you need to refer to an object without knowing its class. It's convenient to reference an object just by its memory address without any type information.
You've already seen one of these anonymous pointers on Initializing Objects:
- (id)
init {
Objective-C defines id as a pointer to an object data structure. (It's much like a void pointer in C, except that the pointer is only used to reference objects.)
So why does the –init method return this generic type? Because you have no guarantee what class of object the superclass will return to you:
if (self = [super init]
) {
During initialization, objects are in a state of flux, so their class is purposely ignored and considered subject to change. Using a type of id expresses the object's lack of identity.
Even though id is nothing more than a pointer to a block of memory, you should never use a void pointer in its place. The compiler is able to perform additional checks and optimize code because the id lets it know that the variable points to an object.
The id type is also used as a way to avoid casting between classes. Some classes need to manage objects without knowing anything about the type of data. A good example of this is collections and other object containers. If objects in a collection were specified with a pointer to an NSObject, you'd have to cast to a subclass each time you retrieved an object from the collection. For lazy programmers, that's a lot of work.
Note
An id also solves the situation with overridden ...
Get iPhone App Development: The Missing Manual now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.