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 trial

iOS

Assign an Array Object to a NSString

Hey All:-),

Challenge #We're at the grocery store shopping and we found the eggs. In the header file we have a property, shoppingCart, of type NSString. In the viewDidLoad method, retrieve the string eggs from the shoppingList array and store it in shoppingCart. Hint: use the 'objectAtIndex' method.

#import "ViewController.h"

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.shoppingList = [[NSArray alloc] initWithObjects: @"toothpaste", @"bread", @"eggs", nil];
    self.shoppingCart = *shoppingList.objectAtIndex:2 ;
}

@end

I'hv tried this challenge like 100 different ways and once i even got it right and moved on to next video but i don't remember what did i do!

so could anyone please tell me how to assign an array object to a NSString?

Thnx In Advance:-)

3 Answers

You need to use NSMutableArray for shoppingCart , so you can add objects to it. then you can add objects of as follows: ''' self.shoppingCart= [NSMutableArray alloc]; [self.shoppingCart addObject:[self.shoppingList objectAtIndex:2]]; ''' /// Another thing, you need to have a pointer to a NSString to be able to assign an object to it, offcourse that object should be of type NSString as well. so first define @property NSString* mystring; in your header. then assign object to it the same way like above: mystring = [self.shoppingList objectAtIndex:2];

Thnx So much Safwat for replying so promptly:-) actually it was specified to create an NSArray only by name shoppingList and then retrieve its 3rd element "eggs" and assign it to an empty NSString named shoppingCart. I tried it further and I got it right this way:

self.shoppingCart = [_shoppingList objectAtIndex:2];

instead of

self.shoppingCart = [*shoppingList objectAtIndex:2];

Or

self.shoppingCart = [self.shoppingList objectAtIndex:2];

I tried that underscore in front of Arrayname only when editor suggested it, so m still kinda confused about how it worked... Seems like we could put underscore in front of ArrayName as well instead of self. or *. Is it?

You are welcome :)

I'm not sure about the impact of using _ , but for sure you should not use *

:-) Oh Okay