Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialVincent Fonade
2,144 PointsWhen you use "self" or "_"
Please could you help me ! I don't really understand the difference between "self" and "_". In the "Creating a @property" video (5:15) it's said : you could use "_predictions" but we don't want to refer directly to instance variable so we use "self.predictions" to refer to the property prediction.
2 Answers
Alex Taylor
2,758 PointsThe keyword 'self' refers to the receiver of the current message, in this case the THViewController. The THViewController has a property which is an NSArray labelled 'predictions'. When an @property is created, setter and getter methods are automatically generated, as well as the corresponding instance variable. The instance variable is preceded by a "_" i.e. _predictions, this is to make it obvious when the instance variable is being referred to, as the property and instance variable are often the same name. Due to the concept of data encapsulation it is best to access ( set or get the value of) the property through setter and getter methods, rather than directly access the property through the instance variable. 'self.predictions' sends the setter method to the instance of THViewController.
Hope that makes sense.
Manuel Palma
6,144 PointsWith the self. you access to the property across the setter and getter methods. With the _ you are directly accessing (direct memory access) to the property.