Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the id type in Objective-C omit the asterisk?

Tags:

objective-c

My understanding of the Objective-C id type is that it's a pointer to an object of unknown type. In my eyes it's like a void* for Objective-C classes with some compiler sugar on top for stuff like type checking. My question is why is it not id* instead of id then since it is a pointer type? If this were Java or C# where object references aren't declared using an * then I wouldn't be so surprised. But in Objective-C, every class is referenced by C-style pointers, so why hide the * for the unknown object type?

like image 949
lmirosevic Avatar asked Sep 28 '12 11:09

lmirosevic


1 Answers

The id typedef is already a pointer:

typedef struct objc_object {
    Class isa;
} *id;

From the Objective-C Programming Language:

In Objective-C, object identifiers are of a distinct data type: id. This type is the general type for any kind of object regardless of class and can be used for instances of a class and for class objects themselves.

id anObject;

For the object-oriented constructs of Objective-C, such as method return values, id replaces int as the default data type. (For strictly C constructs, such as function return values, int remains the default type.)

The keyword nil is defined as a null object, an id with a value of 0. id, nil, and the other basic types of Objective-C are defined in the header file objc/objc.h.

id is defined as pointer to an object data structure:

typedef struct objc_object {
    Class isa;
} *id;

Every object thus has an isa variable that tells it of what class it is an instance. Since the Class type is itself defined as a pointer:

typedef struct objc_class *Class;

the isa variable is frequently referred to as the “isa pointer.”

like image 160
trojanfoe Avatar answered Nov 06 '22 19:11

trojanfoe