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

孤街浪徒 提交于 2020-01-05 10:29:07

问题


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?


回答1:


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



回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/9427237/what-is-the-difference-between-self-variable-and-self-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!