Alex Rivera | Logout

Why [object doSomething] and not [*object doSomething]?

Asked 2010-02-03T02:20:43.123
49

In Objective-C, why [object doSomething]? Wouldn't it be [*object doSomething] since you're calling a method on the object?, which means you should dereference the pointer?

Edit
Report

1 Answer

15

You shouldn't really think of these as pointers-to-objects. It's sort of a historical implementation detail that they are pointers, and that you use them like that in message sending syntax (see @bbum's answer). In fact, they are just "object identifiers" (or references). Let's rewind a little bit to see the conceptual rationale.

Objective-C was first proposed and discussed in this book: Object-Oriented Programming: An Evolutionary Approach. It's not immensely practical for modern Cocoa programmers, but the motivations for the language are in there.

Note that in the book all objects are given type id. You don't see the more specific Object *s in the book at all; those are just a leak in the abstraction when we're talking about the "why." Here's what the book says:

Object identifiers must uniquely identify as many objects as may ever coexist in the system at any one time. They are stored in local variables, passed as arguments in message expressions and in function calls, held in instance variables (fields inside objects), and in other kinds of memory structures. In other words, they can be used as fluidly as the built-in types of the base language.

How an object identifier actually identifies the object is an implementation detail for which many choices are plausible. A reasonable choice, certainly one of the simplest, and the one that is used in Objective-C, is to use the physical address of the object in memory as its identifier. Objective-C makes this decision known to C by generating a typedef statement into each file. This defines a new type, id, in terms of another type that C understands already, namely pointers to structures. [...]

An id consumes a fixed amount of space. [...] This space is not the same as the space occupied by the private da

answered 2010-02-06T20:28:44.163

Your Answer