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:
- id is a reserved keyword.
- It can hold pointer to any object.
- It can hold pointer to nil.
Refer to this In Cocoa, how is the id type defined? for more details...
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
ReplyDeleteThanks for the inputs Johannes..
ReplyDelete