Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between self.var and simply var

What is the difference between using self.var vs. just var in an Objective-C class? Are there benefits or dangers to one or the other?

like image 581
MyNameIsEarl Avatar asked Jan 07 '11 16:01

MyNameIsEarl


People also ask

What is the difference between VAR and let?

let is block-scoped. var is function scoped. let does not allow to redeclare variables. var allows to redeclare variables.

Why is var better than let?

let allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used. This is unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.

What is the difference between LET and VAR in TypeScript?

The let statement is used to declare a local variable in TypeScript. It is similar to the var keyword, but it has some restriction in scoping in comparison of the var keyword. The let keyword can enhance our code readability and decreases the chance of programming error.


2 Answers

self.var calls the property for var. Behind the scenes, Objective-C automatically generates a getter for properties (or you can make one yourself, if so inclined), so self.var uses that getter. Plain var accesses the instance variable directly (i.e., it doesn't go through the getter to get the value).

like image 124
mipadi Avatar answered Oct 02 '22 21:10

mipadi


foo = self.var;
self.var = foo;

is conceptually identical to

foo = [self var];
[self setVar: foo];

So using dot notation, you are really sending messages to self.

foo = var;
var = foo;

is conceptually the same as

foo = self->var;
self->var = foo;

So not using dot notation to access an instance variable is the same as treating self as a pointer to a C struct and accessing the struct fields directly.

In almost all cases, it is preferable to use the property (either dot notation or message sending notation). This is because the property can be made to automatically do the necessary retain/copy/release to stop memory leaks. Also, you can use key value observing with a property. Also subclasses can override properties to provide their own implementation.

The two exceptions to using properties are when setting an ivar in init and when releasing it in dealloc. This is because you almost certainly want to avoid accidentally using a sub class override in those methods and you don't want to trigger any KVO notifications.

like image 45
JeremyP Avatar answered Oct 02 '22 21:10

JeremyP