0

Possible Duplicate:
What is “->” in Objective C?

beginner question here. Im looking through this intro to the objective c runtime (http://mikeash.com/pyblog/friday-qa-2009-03-13-intro-to-the-objective-c-runtime.html) and I see this funky syntax with a ->. Can't seem to find an explanation on what that means.

Easy points anyone?

Thanks!

Community
  • 1
  • 1
Sean Danzeiser
  • 9,141
  • 12
  • 52
  • 90
  • `->` is also known as the ["structure dereference" operator](http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Member_and_pointer_operators). –  Sep 12 '12 at 23:17
  • (I found the duplicate question using the afore-mentioned keywords: "obj-c structure dereference". It is good to first look up the "real name" for something, which I did with searching for "C operator list" initially.) –  Sep 12 '12 at 23:19
  • Objective-C is C. Maybe you should invest in an introductory C programming book/tutorial/class/video/etc. – Jody Hagins Sep 13 '12 at 02:18

1 Answers1

4

That is actually C syntax. It's used to access a field (variable) of a pointer to a struct.

When you have a pointer, you have to use the * syntax to dereference it:

int var = 1;   // regular int variable
int *ptr = &var;  // pointer to that variable
int sum = (*ptr) + 3;   // if you want to use it regularly, you have to dereference it first.

Now, if this pointer happens to be a struct pointer, it can become ugly:

// Define and typedef a struct.
typedef struct {
    int num1;
    int num2; 
} MyStruct;

MyStruct myStruct = (MyStruct){1, 2};   // Regular struct.
MyStruct *pointer = &myStruct;          // Pointer to that struct.
int sum = (*pointer).num1 + (*pointer).num2;   // The ugly part.
int niceSum = pointer->num1 + pointer->num2;   // Same thing with cleaner code.
DrummerB
  • 39,814
  • 12
  • 105
  • 142
  • And in Objective-C and object is a struct and so `->` can be used to access instance variables declared public in the interface. However most will encourage you to use properties and avoid publicly accessible instance variables. – CRD Sep 13 '12 at 01:59