-1

I am new to Objective-C programming, (and C for that matter) and I come from a Java-based programming history. I have some trouble understanding when to use a pointer and when to use a variable instead. My question is this:

Why do I have to type this

NSDate *date = [NSDate date];

Instead of this

NSDate date = [NSDate date];

I feel like I'm not instancing the object, but rather creating its address (or is that the same thing?).

I understand that it makes the program faster to use pass by reference later on, but could someone please clarify the difference as simple as possible for a beginner?

jlehr
  • 15,557
  • 5
  • 43
  • 45
  • 5
    In Java objects are all pointers too, there's just no asterisk. – Brian Bi Jul 19 '14 at 17:00
  • The `[NSDate date]` method is the thing that actually creates a new date object on the heap. The pointer you declare is just used to keep track of the location of the date object. In other words, running alloc init a hundred times would create a hundred objects, you just wouldn't have any way to reference them in the future without keeping a pointer to access them. – CrimsonChris Jul 19 '14 at 17:52
  • See also: [Why does an object variable have to be a pointer?](http://stackoverflow.com/questions/10783089/why-does-an-object-variable-have-to-be-a-pointer?lq=1) – jscs Jul 19 '14 at 19:17

1 Answers1

1

When you allocate an object, the cpu allocates memory in RAM under something called "free-store memory". To access the object in the free-store memory you must use a pointer that points to the memory address of the object.

In Java, memory is still allocated on RAM (as that is how low level hardware stores data), so that doesn't change. The only thing that does change is that Java hides the use of the pointer.

Wenqin Ye
  • 531
  • 1
  • 6
  • 15