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

Currently learning Objective C and my book doesnt seem to do a good job of explaining this line of code. So, i'm aware that we are declaring a pointer "now" that points to an NSDate object. The message is what seems to be confusing me.

If i'm correct, [NSDate alloc] is allocating some memory for an instance of NSDate, but what is init doing?

Girish
  • 4,692
  • 4
  • 35
  • 55
Byron S
  • 99
  • 2
  • 9
  • http://developer.apple.com/library/ios/#Documentation/General/Conceptual/CocoaEncyclopedia/Initialization/Initialization.html – stosha May 28 '13 at 06:46

2 Answers2

0

You are correct about alloc

It allocates memory for an instance of NSDate

init does what it sounds like. It initializes this newly allocated memory. At this point you don't really need to know what init does internally.

Keep learning and when you get to the topic of creating a custom class or subclass, the role of init will become more clear.

Jesse Black
  • 7,966
  • 3
  • 34
  • 45
0

it's very simple ...

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

1.alloc allocates memory for the instance of NSDate i.e now in your code

2.init initializes your instance variable with some default value . if don't use init then your instance may contain some garbage value , to avoid that we usually initialize object with some default value .

Shaik Riyaz
  • 11,204
  • 7
  • 53
  • 70