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 Objective-C Basics (Retired) Introduction to Objective-C Syntax Overview

What are the underscores for?

I see underscores throughout the program. What are they for? Are they pointers, variables, or something else?

Jose Ramos
Jose Ramos
1,908 Points

They are instance variables. We have a Sphere class which is a subclass of NSObject. Our ball is an instance of Sphere: just like Sphere is an instance of NSObject. The _center and _radius can be used to SET and GET info.

In the previous video, he SETS the instance of Sphere (ball) to a radius of 25 using the instance method setRadius, and GETS that (ie, retrieves it) data using radius. Ie, the [ball radius] part of the NSLog line.

1 Answer

Stone Preston
Stone Preston
42,016 Points

if you are talking about variable names with underscores in front of them like this: _variableName those are instance variables.

When you create a property like so:

@property (nonatomic, strong) NSString *myString;

behind the scenes the compiler creates a setter method for that property, a getter method, and an instance variable that is named _myString. This instance variable is really whats behind the property.

A property is really just a way to easily create setter and getter methods for an instance variable without explicitly defining them.

The setter and getter methods access _myString directly so most of the time you never really even use the _myString variable, you just access it using the setter and getter methods.

One of the only times you need to access _myString directly is when you are overriding the setter and getter methods.