When should I be using the self
expression in my iphone development applications? say i have 2 fields: UITextField *text1;
and NSString *str1;
retained and synthesized.
when i am accessing either of these 2 fields, when should i and when should i not use self.text1
and self.str1
?
The self is used to represent the instance of the class. With this keyword, you can access the attributes and methods of the class in python. It binds the attributes with the given arguments. The reason why we use self is that Python does not use the '@' syntax to refer to instance attributes.
The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class.
What is the purpose of the "self" keyword when defining or calling instance methods? self means that no other arguments are required to be passed into the method.
The keyword self is used to refer to the current class itself within the scope of that class only whereas, $this is used to refer to the member variables and function for a particular instance of a class.
self
is not a keyword, it is an expression. Additionally, you use it any time you want to refer to a method or property on yourself, or yourself directly. By "yourself" I am of course, referring to the instance of the class you are operating in.
There are certain circumstances where it's generally discouraged to use the self.
-expression to access a property. Normally you always use self
for any access of a property. It's the most secure and uncomplicated way. Especially if you used retain, then memory management will be done for you.
The two exceptions from this rule:
init
method.dealloc
.In both cases you are dealing with an partially initialized object. There are some side effects that may occur when using setters or getters here -- because they are methods and hence may be overridden.
For example, take a class A
with a property foo
that has been subclassed by class B
. The subclass B
adds an property bar
and overrode the setter for foo
. Now your init
-method calls setFoo:
, because you used self.foo = ...
with some initial value. The subclass, however, also accesses the value of bar
in this setter. But in this case, it may happen that bar has never been initialized and points at some arbitrary data. Calling a setter in init my cause crashes, although the probability may not be too high in your own code.
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