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!
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
I dont understand why self is needed
in objective c i dont understand why the self is needed. please explain
Mike Baxter4,442 Points
Anusha, there are several things going on with self, and they might not all make sense at first. Sometimes you need it, and sometimes you don't. In this video specifically, they're trying to teach you about the difference between sending a message to "self" and sending a message to "super". Let's bring this into the realm of real people for a second, if I tell my "self" to play guitar, then I've been playing guitar for quite a few years and I can do it. But if I tell the "super" of myself (my dad) to play guitar, then I don't think he's ever picked up a guitar, and it's going to sound a lot worse. "self" and "super" are all about who you're talking to when you send messages in Objective-C. Therefore, "self" is used every time I want the current class to send a message to itself, such as,
[self setMyAwesomeVariable:12]; // I could also write this message as the following, self.myAwesomeVariable = 12;
The secret thing that you're not seeing here is that "self.myAwesomeVariable" is actually sending a message, it's not directly setting the "myAwesomeVariable" to 12. The reason it's hard to see that this is happening is because of the "self.myAwesomeVariable" dot syntax—it's all meant to be short, so it sort of hides the fact that it's sending a message to a method. But the reason you want to call "self.myAwesomeVariable" rather than assign it directly is because occasionally you'll do something in that setter method (such as make a note that the variable was changed, just to name a dumb case), whereas if you assign the variable directly you never get the opportunity to do that. Hope that helps!