difference between _var and self.var

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-10 10:12:38

问题


With all this new ARC stuff (which does not fall under NDA…) coming out, it seems like the default for dealing with properties is to set the property without and ivar in the implementation file explicitly until you synthesize it with something like:

@synthesize var = _var;

What's the best practice to use in setting the variable? I know the difference between var and self.var is that self.var is using dot notation and is using the var's setter method.

Is _var just the equivalent of setting it up within the header files like in the good ol' days? Where did that practice of prefacing everything with an underscore come from?


回答1:


_var is just a different name for the instance variable (presumably so you don't accidentally access directly it when you meant to use an accessor). It doesn't have any special meaning in the language beyond just being a valid ivar name.




回答2:


When you define a @property like: @property (nonatomic, strong) NSString *var;, Objective-C 2.0 and above automatically, as of 2012, @synthesizes that property to create three things:

  • An underlying instance variable of NSString *_var.
  • A method for getting the underlying instance variable: -(NSString *)var {}
  • A method for setting the underlying instance variable: -(void)setVar:(NSString *)newVar {}

Generally, it is not good practice to directly access or set the underlying instance variable directly due to messing with KVO and bypassing side effects that might have been placed into either the getter or setter methods.



来源:https://stackoverflow.com/questions/6377365/difference-between-var-and-self-var

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