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!
The independent and dependent variables are the two key variables in a science experiment. The independent variable is the one the experimenter controls. The dependent variable is the variable that changes in response to the independent variable. The two variables may be related by cause and effect.
An experiment usually has three kinds of variables: independent, dependent, and controlled. The independent variable is the one that is changed by the scientist.
There are three main types of variables in a scientific experiment: independent variables, which can be controlled or manipulated; dependent variables, which (we hope) are affected by our changes to the independent variables; and control variables, which must be held constant to ensure that we know that it's our ...
The independent variable is the cause. Its value is independent of other variables in your study. The dependent variable is the effect. Its value depends on changes in the independent variable.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With