Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use the “self” keyword?

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 ?

like image 747
james Avatar asked Nov 02 '10 17:11

james


People also ask

When should I use self in a class python?

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.

Why do we use self in Python?

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 and calling methods?

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.

What is difference between self and this?

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.


2 Answers

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.

like image 104
jer Avatar answered Sep 28 '22 05:09

jer


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:

  • Any init method.
  • In 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.

like image 29
Max Seelemann Avatar answered Sep 28 '22 06:09

Max Seelemann