问题
I am quite new to Objective C and iOS, currently trying to learn app development using the iOS 6 SDK. One concept I really can't wrap my head around is the difference between "_variable" and "self.variable" when being accessed in the .m file. Are they the same? Or different?
Following is a simple sample
MyClass.h
#import <Foundation/Foundation.h>
@interface MyClass : NSObject
@property (strong, nonatomic) NSString *myName;
@end
MyClass.m
#import "MyClass.h"
@interface MyClass ()
@property (nonatomic, strong) NSString *anotherName;
@end
@implementation MyClass
- (void) myFunction {
_myName = @"Ares";
self.myName = @"Ares";
_anotherName = @"Michael";
self.anotherName = @"Michael";
}
@end
So is there a difference in the above implementations to set a variable? Variable "myName" is Public while "anotherName" is Private.
Would greatly appreciate any inputs. Thanks!
回答1:
The difference is that:
the variable names with _ are instance variables.
self.variable is calling a getter method on your object.
In your example, the instance variables are automatically generated and you don't need to synthesize your properties either.
The real important difference in your example comes into play if you are not using ARC-
self.variable will retain an object for you if you mark the property with retain or strong
_variable does not address memory management at all
来源:https://stackoverflow.com/questions/15129795/whats-the-difference-between-variable-self-variable-in-objective-c