Object Confusion first sec of Chapter 12


#1

I slammed into a wall at this line of code.

NSDate *now = [NSDate date];

This is what I think I know about this code, but I suspect I don’t understand what is happening here.

*now is a pointer. [] encompasses a message. NSDate is a class. date is a method inside NSDate (not because its in brackets with NSDate, but by its declaration somewhere).

I think that the essence of a message is to specify a class and a method in brackets, and that [] syntax will return the results of the message. Not unlike calling a function.

The part that seems most confusing is that NSDate is on both sides of this assignment statement. I think that *now becomes a pointer with the type NSDate, and I get that classes can generate instances of themselves. So I’m guessing that NSDate *now acts kind of like a C declaration where NSDate is a type and *now is the name of the variable, in this case a pointer to an object with the type NSDate.

As a result, a variable now contains the current date as an NSDate object, correct?

I’ve looked at the stack in the debugger, and the NSDate class reference, and this explanation sort of feels right, but I’m not sure. Its as if the moving parts in the code, which have made sense every step of the way until now, have suddenly become opaque.

Any help would be greatly appreciated. Thank you.
Bob


#2

Your understanding is correct.

The statement:
NSDate * now = [NSDate date];
Does the following:

  1. Declares the now variable, a pointer, for holding the address of (the pointer to) an object of type NSDate;
  2. Invokes the method date (a class method) on the NSDate class object to create an NSDate object and to get the pointer to it;
  3. Assigns the pointer to the newly created object to the now variable.

Though rare, the above statement can also be written like this:
NSDate * now ; // declare pointer variable
now = [NSDate date]; // create object and assign its address (the pointer to it) to the variable

Note: NSDate is not only a type, it is also an object (a special kind of object, a class object;there is only one instance of it in a program.)


#3

Wow the fact that NSDate is both a type and an object class really cements my understanding. I didn’t realize that was possible. Thank you!

Bob