Why no alloc and init for NSDate object?


Wow, first post in the forum for the new book. I am honored.

I am enjoying the new book, just a couple questions…

On bottom of page 51

       // Create the date object
        NSDate *now = [[NSDate alloc] init];
        NSCalendar *cal = [NSCalendar currentCalendar];
        NSDateComponents *weekComponents = [[NSDateComponents alloc] init];

Why don’t I have to alloc and init the NSCalendar object “cal”?

On top of page 52

            // Create a date/time object that is i weeks from now
            NSDate *iWeeksFromNow;
            iWeeksFromNow = [cal dateByAddingComponents:weekComponents toDate:now options:0];

Why don’t I have to alloc and init the NSDate object “iWeeksFromNow”?

Thanks in advance,


It’s because those methods return pointer to already existing objects. alloc+init creates new instance of particular class. You don’t need that here, because you only want to store address of existing object (which is created by method currentCalendar or dateByAddingComponents:toDate:options: so your alloc+init is in fact in those methods, you just don’t see it).

Basically these methods are there to return you object that was in some way manipulated or contains information from API. I still haven’t got time for the book, but I am sure it will be also explained in memory management part. Those methods are returning autoreleased objects which you don’t really own since you haven’t allocated them by yourself. Sorry if I confused you, but I am sure you will get it :slight_smile:



Thanks for the quick feedback. That makes sense. The NSCalendar class methods are creating the objects and auto-releasing them prior to returning them. I would need to retain them or assign them to instances I allocated, if I wanted to keep them. But since I am just using them as intermediate steps to get to each entryDate, I don’t need to retain or assign them.



Bsically a class can define two types of methods:

  • instance methods
  • class methods

If you are familiar with other languages like Java or C#, you should be familiar with the concept of class methods. There they are called static functions.

The method currentCalendar is a class method. That is, it is part of the class, and not part of any given instance of the class. What this means to the consumer of the class, is that he/she can call the method without needing an instance of the class.

By the way, the method alloc is another example of a class method.