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 trialSamir Govani
Courses Plus Student 977 Pointsthviewcontroller self
"The current instance of thviewcontroller has a property called label and in this case thviewcontroller is represented by self which indicates that it is the instance of our thviewcontrol. And propererty here is prediction label, thats what we named our IBOutlet. " I was wondering if you could more clearly explain what you are saying here. I don't understand the part about thviewcontroller being represented by self.
2 Answers
Stone Preston
42,016 Pointsself represents an instance of the current class in instance methods, and the class itself in class methods. Its kind of hard to understand, but when implementing a class such as a view controller, sometimes you want to call some instance methods or reference some instance variables inside the class itself. for example. if we had a class named cat
@implementation Cat
- (void)meow {
NSLog(@"meow");
}
you can see that Cat has an instance method called meow. lets add another method called eat that calls that meow method inside it. But since meow is an instance method, which are called on instances or objects, how do we call that method when we dont have an instance to call it on since we are currently implementing the class itself? The solution is to use the keyword self which represents an instance of the current class.
- (void)eat {
NSLog(@"eating");
[self meow];
}
using [self meow] basically says call the meow instance method on the current instance of Cat. in other languages instead of the keyword being self the keyword is this, which is a bit easier to understand. in java if we wanted to call the meow method we would use this.meow() where this refers to "this instance of cat"
when working inside class methods, using self just refers to the class itself. So you can use self to call class level methods etc. this way of using self is a lot easier to understand since its more simple. if you need to call a class method or refer to the class itself inside a class implementation, you can just use self ie [self someClassMethod]
Samir Govani
Courses Plus Student 977 PointsThanks! your relationship to Java helped a lot!