Tuesday, September 10, 2013

What is "id" in Objective C

id

'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. 

syntax:

id newPointer = somepointer;

e.g.


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:


-(id)init 

  {
    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.


Summary:
  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... 



2 comments:

  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

    ReplyDelete