Tuesday, September 10, 2013

What is "id" in Objective C


'id' is a typedef in objective C. This means "Pointer to an Object". This Object can be any object of Objective C.

typedef struct objc_class *Class;
typedef struct objc_object {
    Class isa;
} *id;

typedef struct objc_selector    *SEL;    
typedef id          (*IMP)(id, SEL, ...); 

id can hold pointer of any kind of object. 


id newPointer = somepointer;


NSString *str = @"karm";

id newStr = str;

It will work perfectly. Here is something you should note that id keyword is not followed by an *, its because id already knows that it is a pointer.

We use this while return objects from the derived class while we overrige the init method as shown below:


    if (self = [super init])
       someIVarObject = [SomeClass alloc] init];
    return self;


Here we return id because somebody can initialize an object like this.

BaseClass *base = [[DerivedClass alloc] init];

In this case we want to make sure we have the right pointer returned from the init method.

  1. id is a reserved keyword.
  2. It can hold pointer to any object.
  3. It can hold pointer to nil.
Refer to this In Cocoa, how is the id type defined? for more details... 


  1. id is not a reserved keyword. It's normal C typedef. For more information Cmd+Click ob it or consult eg StackOverflow http://stackoverflow.com/questions/1990695/in-cocoa-how-is-the-id-type-defined

  2. Thanks for the inputs Johannes..