Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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?

ViewController.h
#import "UIViewController.h"

@interface ViewController : UIViewController

@property (strong, nonatomic) NSString *shoppingCart;
@property (strong,nonatomic) NSArray *shoppingList;

@end
ViewController.m
#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
Chris Shaw
26,650 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,650 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.