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 trial

iOS

“_” vs “.” with variables

What is the difference when accessing a class instance variable when using _variable vs self.variable? I was writing a setter method and self.variable = anotherVariable didn’t work, yet _variable = anotherVariable worked… Why is that?

2 Answers

The difference between accessing instance variables with _instanceVariable and accessing with self.instanceVariable is that _instanceVariable is accessing the instance variable directly. The reason you couldn't set the instance variable in the setter method by writing self.instanceVariable = anotherVariable is that you can't set the instance variable in the setter method with the setter method. It just doesn't work that way. When you are using self.instanceVariable you are using the setter method to access the instance variable rather than accessing it directly.

You would access your instance variables by doing _instanceVariable only in the getter, setter and init methods. Anywhere else you would write self.instanceVariable.

Hope this clears things up.

Yes it makes sense! Thanks a ton!