1

I have seen accessing variable in iphone sdk with -> or . symbol.Which one is the best?what is the difference between self.variable and self->variable?

nameless
  • 809
  • 3
  • 9
  • 27
  • For an explanation of what happens when using the dot notation and properties with synthesize, see [this](http://stackoverflow.com/questions/8576593/objective-c-memory-management-of-instance-members/8576760#8576760) – Nick Bull Feb 24 '12 at 08:31

3 Answers3

3

The dot-notation goes through the accessor, the arrow notation goes directly to the instance variable. Try this code:

@interface Foo : NSObject
@property(assign, nonatomic) NSInteger bar;
@end

@implementation Foo
@synthesize bar;

- (void) setBar: (NSInteger) newBar
{
    NSLog(@"Setting new bar.");
    bar = newBar;
}

- (id) init
{
    self = [super init];
    self->bar = 5; // doesn’t log anything
    self.bar  = 6; // logs
    return self;
}

@end
zoul
  • 102,279
  • 44
  • 260
  • 354
0

The dot notation will use the properties getter/setter methods - so dependant on what you have declared the variable may be retained or assigned or you can specify your own getter / setter methods to do extra work whenever that property is set.

self-> is a pointer reference to self. Which accesses the var directly. I personally don't see the point in using it in obj c as just 'var on it's own' will have the same effect.

ps. There are a ton of other questions/answers on this exact subject here on SO.

This one

This one

Community
  • 1
  • 1
Damo
  • 12,840
  • 3
  • 51
  • 62
0

self.varmeans you declare a property for var,supposing like:


@property (nonatomic, retain) id var;

it in fact calls [self var] for self.var.

While self->var just gets the member value of self instance like you do in C++ or else.

scorpiozj
  • 2,687
  • 5
  • 34
  • 60