Nested messages

I want to make sure I’m understanding this simple line of code.

NSDate *now = [[NSDate alloc] init];

  1. I am creating an instance of an NSDate object that is a pointer.

  2. I am allocating memory for it.

  3. I’m not entirely sure what initialization does. Init is still kind of fuzzy to me. Is it assigning a value to it so that it can be used ?

[quote]1. I am creating an instance of an NSDate object that is a pointer.

  1. I am allocating memory for it.
    [/quote]
    What you are saying is basically correct, but it is more accurate to simply say: I am creating an NSDate object (which is an instance of NSDate class.)

[quote]3. I’m not entirely sure what initialization does. Init is still kind of fuzzy to me. Is it assigning a value to it so that it can be used ?
[/quote]
The creation process consists of two phases: memory allocation and initialisation.

An NSDate object itself is not a pointer, but it is a piece of information, which resides at some (unique) memory address. When you allocate the object, a block of memory (of suitable size) is allocated for the object to live in. But only allocating memory is not enough; you need to put the object in a known state, its initial state; this is called the initialisation.

Create an object - Allocate and initialise:

// Create a FooBar
FooBar *fooBar = [[FooBar alloc] init];

The above code is equivalent to:

// Allocate room in memory for a FooBar
FooBar *fooBar = [FooBar alloc];

// Put fooBar in its initial state so that it becomes ready for use
fooBar = [fooBar init];

This process is very similar to buying a new computer or phone (allocation), and setting it up (initialisation) before you can start using it.

[Become a competent programmer faster than you can imagine: pretty-function.org]