3

I have just started using Objective C and although I am doing okay with the pace and learning curve (I have no C background) - I don't understand one concept which is also part of C++ - Pointers!

OK - I understand that pointers point to the physical location of the actual variable rather then the value for the variable itself. When on earth can that come in handy?

Also, when to use them and when not to?

I have Googled enough but every guide I come across seems to assume that I am a PhD in rocket science.

Can someone please explain this with a simple example?

alicjasalamon
  • 4,171
  • 15
  • 41
  • 65
Sean
  • 1,151
  • 3
  • 15
  • 37

3 Answers3

2

One of the main reasons that pointers are used is to save memory. For example if you are passing an array to a function, it would be better to send the address in memory to the function rather than sending the values.

If you go on to do c or other lower level languages, then you will see that arrays and pointers are almost interchangeable. (C-style arrays, not NSMutableArrays in objc or vectors in c++ or lists in c# etc)

tomelse
  • 90
  • 6
2

Although they are C pointers of course, I strongly suggest to understand them als references to objects.

You either create an object or receive it from somewhere and store a reference to the object in a varialbe.

When you hand the reference to the object to some function or method then this method can access the very object that you handed over. It does not nesessarily have to work with a copy of the data. If it makes changes to the ojects' properties (as far as allowed by means of the poperty declaration and stuff) then the very object is changed that your reference is referring to.

You can of course copy it and continue working with that copy when ever you think it is suitable. In that case the original object remains unchanged.

When you really come into a situation where you have to work with c-style pointers then you better step back and understand C. I donnot think it is wise understanding c-style pointers while coming from an Objecive-C background. Clear your mind and learn C from scratch and after that make use of the new know how in that very very rare situations where you have to deal with these basic data types in Objective-C projects.

Hermann Klecker
  • 14,039
  • 5
  • 48
  • 71
1

Here is a simple reason:

Imagine you have a really big object. - When you pass it to a function do you really want to copy & duplicate the entire object? - This would take a lot of CPU and memory.

By using pointers you do not have to copy the original object every time you pass it around. (Ofcourse the flipside is that if you change the object in the function it will change the original object as well).

andy boot
  • 11,355
  • 3
  • 53
  • 66
  • Thanks a lot Andy! I finally understand the purpose - I thought it was a legacy thing that people just couldn't quit the habit of using it - how wrong was I? – Sean Sep 10 '12 at 10:07