Guido Anselmi
Guido Anselmi

Reputation: 3912

What does the '->' operator signify in Objective C?

XCode just corrected my use of the . operator to the -> operator.

I have searched around to find a definition or documentation for the -> operator but could find any.

I am trying to emulate a Java-style of instance variable. Specifically I am initializing an instance with a provided configuration object which I want to keep around for subsequent use after the method initializeService has executed.

A good answer to this question would provide a comparison with Java instance variable declaration and subsequent assignment via an instance method.

Code before XCode correction:

#import "MY_Service.h"
#import "MY_Configuration.h"

@implementation MY_Service {

    MY_Configuration *configuration;

}

-(void)initializeService:(MY_Configuration *)configuration
{
    self.configuration = configuration;

}


@end

Code after XCode correction:

#import "MY_Service.h"
#import "MY_Configuration.h"

@implementation MY_Service {

    MY_Configuration *configuration;

}

-(void)initializeService:(MY_Configuration *)configuration
{
    self->configuration = configuration;

}


@end

Upvotes: 0

Views: 98

Answers (3)

jlehr
jlehr

Reputation: 15597

Objective-C instance variables are ordinarily prefixed with an underscore. If you change your declaration to follow this convention you can rewrite your assignment as

_configuration = configuration;

With respect to whether it would be better to declare a property or an instance variable, there are no absolutes here, but property declarations do have certain advantages. Some examples would be allowing you to specify additional things such as copy semantics for memory management, atomicity, etc. But your code correctly declares a private instance variable that would work as you expect.

Upvotes: 2

Carl Norum
Carl Norum

Reputation: 224844

The -> means the same thing in Objective-C that it does in C. That is:

a->b 

is equivalent to

(*a).b

Upvotes: 4

Mohannad A. Hassan
Mohannad A. Hassan

Reputation: 1648

-> is used to access instance variables, the same way it's used to access member variables of a pointer in C or C++.

In the code you provided, you declared configuration as an instance variable. If you wanted to use the dot operator, you should have declared it as a property, which is what you really should have done from the beginning.

Upvotes: 2

Related Questions