What is the difference between ‘->’ (arrow operator) and ‘.’ (dot operator) in Objective-C?

-> is the traditional C operator to access a member of a structure referenced by a pointer. Since Objective-C objects are (usually) used as pointers and an Objective-C class is a structure, you can use -> to access its members, which (usually) correspond to instance variables. Note that if you’re trying to access an instance variable from outside the class then the instance variable must be marked as public.

So, for example:

SomeClass *obj = …;
NSLog(@"name = %@", obj->name);
obj->name = @"Jim";

accesses the instance variable name, declared in SomeClass (or one of its superclasses), corresponding to the object obj.

On the other hand, . is (usually) used as the dot syntax for getter and setter methods. For example:

SomeClass *obj = …;
NSLog(@"name = %@", obj.name);

is equivalent to using the getter method name:

SomeClass *obj = …;
NSLog(@"name = %@", [obj name]);

If name is a declared property, it’s possible to give its getter method another name.

The dot syntax is also used for setter methods. For example:

SomeClass *obj = …;
obj.name = @"Jim";

is equivalent to:

SomeClass *obj = …;
[obj setName:@"Jim"];

Leave a Comment