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) Advanced Objective-C Memory Management

I dont understand why self is needed

in objective c i dont understand why the self is needed. please explain

3 Answers

Mike Baxter
Mike Baxter
4,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!

.

Mike Baxter
Mike Baxter
4,442 Points

You can actually set a variable through "self.me" and through regular "me". The difference is, the later sets just the variable, whereas the first calls the setter method, which may do something more than just set the variable; it may update something else. That's why "self.me" is preferred, because you have less to worry about in that case.

thanks