Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

iamkoby

macrumors newbie
Original poster
Aug 31, 2009
1
0
Hello everyone!

I am new to Objective-C and iPhone development but already program 5+ years in PHP with extensive OOP knowledge.
However I am struggling to understand the concept of pointers that is extensively used in objective-C programs.

I understand that pointers are pointing to the actual address in memory of where the variable rests but I don't understand why should I care.

Why should I assign a variable the address and not the actual result?

Why this:

Code:
NSString *myText = [[NSString alloc] init];

and not this:

Code:
NSString myText = [[NSString alloc] init];


Thanks for your answers!
 
Because those are the rules. Objective-C objects must be allocated on the heap and cannot be allocated on the stack. The compiler will object if you try it.

Is there a good reason for this or a deep reason for this? Not really sure. I think it has to do with automatic calling of constructors and destructors. The code you showed demands a copy constructor to return an object as a struct. This exists in C++ but not in Obj-C. I guess the designers of Obj-C went for simplicity in the language design and this is a side effect.
 
Because pointers let you do some pretty powerful stuff, although it's not obvious with strings. It may be obvious with other "mutable" (changeable) objects. For example:

Code:
Reservation *a = [[Reservation alloc] init];
Reservation *b = a;

I have two pointers, but only one reservation object. If I call [b cancelReservation] it's the same as calling [a cancelReservation] . This is powerful stuff - it means I can pass the address of an object (just the pointer) into a method and have full control of the orginal object. It also means I can put a pointer into an array, pull it out later, and have full control of the original object.

If objects didn't use pointers, but instead they created a copy of the object every time you did an assignment just like ints and floats do, you'd be unable to pass them to methods or store them in arrays in a useful way.
 
Maybe this explanation of stack vs heap will help you understand why you want to use the heap when possible. Specifically the last three paragraphs.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.