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

iOS Build a Simple iPhone App with Objective-C Creating a Data Model Creating a Data Collection

How 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;

#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];


3 Answers

Chris Shaw
Chris Shaw
26,676 Points

Hi 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!

Thanks Chris. That Worked. Thanks a lot !!

Laurie Gray
Laurie Gray
23,119 Points

Thanks 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
Chris Shaw
26,676 Points

The keyword self provides context to our class instance, in many different languages compilers will have two main scopes.

  1. The global scope, in this case that's self
  2. 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.