I’m new to iPhone development, and am sort-of getting there with pointers in Objective-C. Can anyone briefly explain pointers to me? I know that some native C types don’t need pointers (i.e. are weakly typed), such as int.
Also, what’s the difference between:
NSDate* theDate = [NSDate date];
and:
NSDate *theDate = [NSDate date];
?
Thanks again StackOverflow!
There’s no difference between those two things. The asterisk denotes a pointer but may have whatever whitespace you like either side of it. E.g. the following is also valid:
The creators of Objective-C chose to add objects to C by keeping them all on the heap (ie, they’re things you explicitly create and destroy — there’s no such thing as a local object in Objective-C) and referring to them via pointers. Pointers are just memory addresses. So ‘NSDate *’ isn’t an NSDate, it’s just a record of where in memory an NSDate object lives. Exactly like the difference between a street address and a house.
Primitive operations (like addition, multiplication, etc) work only on C primitive types, like int, short, float, etc. Technically the pointers you keep to Objective-C objects are primitive types, because the thing you actually have is the address not the object. But they’re not generally very useful.
You operate on objects only by sending messages to them. The square bracket syntax means ‘send this message to this object’. Which, when you’re just starting, is sufficiently like a function call to just think of it as that. There’s a distinction in that some things C does at compile time, Objective-C does at runtime. But you can just trust that they’re being done for now.
Objective-C is relatively typeless — you declare pointers as being of a particular type but the operations you perform on them (ie, sending messages) act in exactly the same way irrespective of the type. That’s why the ‘id’ type (which means any object) can exist. Objective-C is weakly typed in the sense that a variable of type id can have a pointer to any object assigned to it.
In practice, all objects descend from NSObject so it’s often more useful to use NSObject * and an explicit cast when type hopping. That means you can use the things NSObject adds without compiler warnings, including Objective-C’s reference counted memory stuff, the things for finding out whether an object can perform a particular message and so on.