Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between _variable & self.variable in Objective-C? [duplicate]

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!

like image 737
ares05 Avatar asked Feb 28 '13 07:02

ares05


People also ask

What are the differences between variables?

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.

What are the 3 Types of variables?

An experiment usually has three kinds of variables: independent, dependent, and controlled. The independent variable is the one that is changed by the scientist.

What is the difference between the 3 variables?

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

What are the differences of independent and dependent variables?

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.


1 Answers

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

like image 184
Jesse Black Avatar answered Sep 26 '22 01:09

Jesse Black