Objective-C Language Basic Data Types id

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!


id is the generic object pointer, an Objective-C type representing "any object". An instance of any Objective-C class can be stored in an id variable. An id and any other class type can be assigned back and forth without casting:

id anonymousSurname = @"Doe";
NSString * surname = anonymousSurname;
id anonymousFullName = [NSString stringWithFormat:@"%@, John", surname];

This becomes relevant when retrieving objects from a collection. The return types of methods like objectAtIndex: are id for exactly this reason.

DataRecord * record = [records objectAtIndex:anIndex];  

It also means that a method or function parameter typed as id can accept any object.

When an object is typed as id, any known message can be passed to it: method dispatch does not depend on the compile-time type.

NSString * extinctBirdMaybe = 
               [anonymousSurname stringByAppendingString:anonymousSurname];

A message that the object does not actually respond to will still cause an exception at runtime, of course.

NSDate * nope = [anonymousSurname addTimeInterval:10];
// Raises "Does not respond to selector" exception

Guarding against exception.

NSDate * nope;
if([anonymousSurname isKindOfClass:[NSDate class]]){
    nope = [anonymousSurname addTimeInterval:10];

The id type is defined in objc.h

typedef struct objc_object {
    Class isa;
} *id;

Got any Objective-C Language Question?