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

Pascal Hausberger
Pascal Hausberger
16,453 Points

Difference between _ivar and self.var ?

Hi Ben Jakuben Amit Bijlani Pasan Premaratne !

Sorry for this rather basic question, but I still get confused by following:

What is the difference between something like _photo and self.photo?

Aren't they both instance variables?

As far as I understand i use _photo for following situation: @interface ExampleClass: NSObject @property(...) NSString *photo; ... So by using _photo, i am accessing the string photo of the class ExampleClass, am i correct?

but isn't self.photo referring to ExampleClass too? Isn't self.photo the same as ExampleClass.photo?? So are they the same?

Thanks for your help!

3 Answers

Stone Preston
Stone Preston
42,016 Points

_ivar accesses the variable directly. using self.ivar uses the getter/setter methods (using self.ivar is really using [self ivar]/ [self setIvar]) which then access the ivar ( _ivar is created behind the scenes thanks to your @property declaration)

so I could get the value of an ivar using _ivar, or I could use self.ivar which would call its getter method which looks like this (assuming your ivar was a String object)

- (NSString *)ivar {

return _ivar;

}
Pasan Premaratne
Pasan Premaratne
Treehouse Teacher

Right. And the reason that you can access the ivar is because the property declaration in your header file instructs the compiler to create the backing ivar at runtime.

Stone Preston
Stone Preston
42,016 Points

edited answer to include that info. thanks

Troy Fine
Troy Fine
7,592 Points

I love it when I randomly visit forum post and find things like this. I learn just as much from the forums as I do from the tracks. Got to love the treehouse community.

Pascal Hausberger
Pascal Hausberger
16,453 Points

Great, I understand now! Thanks so much guys!! :)