When to use `self` in Objective-C?

Now that it has been more than 5 months now when I am in Objective-C, I also have my first application published on the App Store, but I still have doubts about the basic functions of the language.

When should I use self access to iVars, and when should I not?

When you release the outlet, you write self.outlet = nil in viewDidUnload, instead you write [outlet release] in dealloc . Why?

+4
source share
4 answers

When you write self.outlet = nil , the [self setOutlet:nil]; method is called [self setOutlet:nil]; . When you write outlet = nil; , you directly access the variable outlet .

if you use @synthesize outlet; , then the setOutlet: method is automatically generated, and it frees the object before assigning a new one if you declared the property as @property (retain) NSObject outlet; .

+6
source

A very important blog for understanding the properties of the getter-setter method in a c object

  Understanding your (Objective-C) self 

http://useyourloaf.com/blog/2011/2/8/understanding-your-objective-c-self.html

+3
source

You use self when referencing @property. Usually it will be @ synthesize'd.

You do not use self if you refer to the variable "private". Typically, I use properties for user interface elements, such as UIButtons, or for elements that I want to easily reach from other classes. You can use the @private, @protected modifiers to explicitly provide visibility. However, you cannot use private methods that are not in Objective-C.

The part about nil, release, and dealloc is not related to using the self. You are freeing what you have saved, you are zero, which is auto-dependent.

You should read the Objective-C guide , it is well written and very useful.

+1
source

You are using self. when you access the properties of the class you are in (hence me). Basically, you use self when you want to keep the value, but only if you saved the properties in your definition.

release just frees the object you saved. You should not release what you have not saved, because this will lead to a crash (zombie object).

0
source

All Articles