简体   繁体   中英

What is the difference between self.variable and self->variable?

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?

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

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

self.var means 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM