简体   繁体   中英

difference between _var and self.var

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?

_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.

When you define a @property like: @property (nonatomic, strong) NSString *var; , Objective-C 2.0 and above automatically, as of 2012, @synthesize s 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.

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