Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

self.variable and variable difference [duplicate]

What is the difference between self.myVariable = obj; and myVariable = obj;, when I use @propery/@synthesize to create `myVariable?

like image 656
Shyne Avatar asked Feb 11 '09 11:02

Shyne


People also ask

What is a self variable?

The self variable is used to represent the instance of the class which is often used in object-oriented programming. It works as a reference to the object. Python uses the self parameter to refer to instance attributes and methods of the class.

Can we replace self in Python?

self is only a reference to the current instance within the method. You can't change your instance by setting self .

Why do we not use the self operator to access class variables?

However, it's not required with a static method. Because, the static methods are self sufficient functions and they can't access any of the class variables or functions directly. Let's look at a complete example with self and cls variables and a static method without any arguments.

How do you pass a value to yourself in Python?

Self is the first argument to be passed in Constructor and Instance Method. Self must be provided as a First parameter to the Instance method and constructor. If you don't provide it, it will cause an error.


1 Answers

It's important to note that dot-syntax is converted to a simple objc_msgSend call by the compiler: that is to say that underneath it acts exactly like a message send to the accessor for that variable. As such, all three of the following are equivalent:

self.myVariable = obj;

[self setMyVariable:obj];

objc_msgSend(self, @selector(setMyVariable:), obj);

Of course, this means that using dot-syntax actually results in a full message send, meaning calling a new function and all the overhead that is associated with it. In contrast, using simple assignment (myVariable = obj;) incurs none of this overhead, but of course it can only be used within the instance methods of the class in question.

like image 182
rpj Avatar answered Sep 20 '22 15:09

rpj