PDA

View Full Version : When to use pointers?




grimreaper1377
Apr 16, 2009, 10:32 PM
Hello,

I'm fairly new to (obj)c and the main obstacle ive encountered is knowing when to use pointers. Is there any rule? In a lot of sample code from books and screencasts, "int"s and "float"s aren't pointers, while everything else is...Any suggestions?

Thanks!



Krevnik
Apr 16, 2009, 10:51 PM
All Obj-C objects are referenced by pointers. There is no real way around it. The retain/release mechanism is how you deal with an object's scope.

Beyond that rule, the standard C guidelines on when to use pointers apply.

grimreaper1377
Apr 16, 2009, 11:23 PM
So basically, all objects must use pointers?

Beyond that rule, the standard C guidelines on when to use pointers apply.

Where can I find these guidelines?

lee1210
Apr 16, 2009, 11:28 PM
I think some background in C will help. I guess in my mind a pointer is just a tool. When do you use a hammer? When that's the appropriate tool. A pointer is a memory address, the type of the pointer indicates how many bytes are at the other end and how they should be interpreted. If you need to point to an int that isn't local to a given scope you would use an int pointer. If you need to pass a variable to a function and have its value modified in said function, you'd need to pass a pointer.

It happens that in Objective-C all objects are accessed via pointers as well, but this is the easiest application of pointers to deal with. You never need to reference or derference an object *, you don't have to track the memory in use on the other end of it in the same manner, etc.

-Lee