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 trialLaurie Gray
23,119 PointsThe use of 'self' in Objective C
Could someone please help me to (in a very simple way) grasp the use of 'self'? Why do we need to quote self? I think it may have something to do with scope but not entirely sure. Many thanks! :)
#import "UIViewController.h"
@interface ViewController : UIViewController
@property (strong, nonatomic) NSString *shoppingCart;
@end
#import "ViewController.h"
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Add your code below!
}
@end
2 Answers
Chris George
9,373 PointsHey Laurie, I don't really know objective c that well, but I do know swift (the other language to make iPhone apps), and the keyword self is the same in these two languages.This concept in particular was very difficult for me to grasp, but now I realize it is a lot simpler than I was making it out to be. The keyword self is just used to refer to the object itself that is using the keyword in its class. If I had a property called height for example, and I wanted to access it, to avoid confusion I would access it by self.height. Just try to think of it as being a way to explicitly say what "height" you are talking about. If you had another local variable called height in a function, and you wanted to access the property called height (not the local variable), then I couldn't just say height. The reason is the compiler would think you were referring to the local variable that you had called height. To avoid the confusion, you would specify that you wanted the class property. To refer to the class you are in, you use the keyword self, then the property name of the class that you are in. I hope this sort of makes sense and if you need any clarifying details, just ask.
Laurie Gray
23,119 PointsHey Chris, the community on here is ridiculously good. Thanks for your answer also and I think I kind of understand what youre saying and I guess with more experience Ill just grasp it but I like that you've made it sound simple!
Have a great day man!