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 trialFaizan Mohammed
2,036 PointsHow to assign NSString shoppingCart value to the object at index 2 .. that is "eggs" ?
can i do it using self method?
#import "UIViewController.h"
@interface ViewController : UIViewController
@property (strong, nonatomic) NSString *shoppingCart;
@property (strong,nonatomic) NSArray *shoppingList;
@end
#import "ViewController.h"
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Add your code below!
self.shoppingList=[[NSArray alloc]initWithObjects:@"toothpaste",@"bread",@"eggs",nil];
self.shoppingCart=[shoppingList objectAtIndex:2];
}
@end
3 Answers
Chris Shaw
26,676 PointsHi Faizan,
You have a minor oversight in your code which is you haven't added self
before shoppingList
which will cause a syntax error as there's no variable in the local scope called shoppingList
.
self.shoppingCart = [self.shoppingList objectAtIndex:2];
Happy coding!
Faizan Mohammed
2,036 PointsThanks Chris. That Worked. Thanks a lot !!
Chris Shaw
26,676 PointsNo worries.
Laurie Gray
23,119 PointsThanks for the help here. Could you please outline why we need to use self please? I understand we're telling the program we're using shoppingCart and shoppingList so why do we need self and what is self actually referring to? Sorry for dumb questions!
Chris Shaw
26,676 PointsThe keyword self
provides context to our class instance, in many different languages compilers will have two main scopes.
- The global scope, in this case that's
self
- and the local scope, these are variables defined with a function.
In Objective-C and Swift self
is always required when you have a local variable defined that has the same name as an class property.
Hope that helps.