I’m still getting confused by Objective-C. Sometimes you declare a variable like so:
NSRect rect;
And sometimes like so:
NSValue *value;
I never know when to add the *, so far I always looked it up in Apple’s documentation. I know the difference is between a value and a pointer to an object.
But are there any hard and fast rules as to when I declare a value and when I declare a pointer? Something to make it easier to remember? Or do I have to know (eg. look up) which NSSomething is a value and which is an object?
Thank you!
Short and simple: yes, you have to remember this for each type, but it will come very naturally after a little while.
It’s not so much a question of “which NSSomething is a value and which is an object” (more accurately: which NSSomething is a scalar datatype or a struct and which is a class), though. Even though you won’t see or use declarations like:
very often, they are perfectly valid and necessary at times. So for scalars (simple datatypes like NSInteger) and structs, both variants are valid and which one you use depends on whether you need a pointer or the actual thing.
With objects, all your variables must always be pointers because objects can only be allocated on the heap and not on the stack. So unlike the examples above, this:
is not correct and will not compile.