What is the difference between self.myVariable = obj;
and myVariable = obj;
, when I use @propery
/@synthesize
to create `myVariable?
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.
self is only a reference to the current instance within the method. You can't change your instance by setting self .
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.
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.
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.
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