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 Objective-C Basics (Retired) Foundation Framework NSArray

Judy Tsai
Judy Tsai
6,376 Points

Can not create String pointing to array element directly

Hi,

I followed the steps to create the NSString *thang, but received

error: Semantic Issue: Initializing 'NSString *' with an expression of incompatible type 'NSArray'

The code looks like this

    NSArray *foo = [[NSArray alloc] initWithObjects: @"f", @"o", @"o", nil];
    NSLog(@"%@", foo);
    //use for loop to print individual item in array
    for (NSString *string in foo){
        NSLog(@"%@", string);        
    }
    NSString *thang = foo[2];
    NSLog(@"%@", thang);

What am I missing here?

Thank you!

4 Answers

Stone Preston
Stone Preston
42,016 Points

maybe try:

NSString *thang = [foo objectAtIndex:2];
Judy Tsai
Judy Tsai
6,376 Points

Hi, Stone,

That worked! Thank you!

I also ran on NSMutableArray, when I declare array and assign value like this:

NSMutableArray *lots = [[NSMutableArray alloc] init];
    lots[0] = @"bravo";
    lots[1] = @"lima";

I got the error of

Semantic Issue: Assigning to 'NSMutableArray' from incompatible type 'NSString *'

Do I need to declare individual NSString? Am I missing something here again?

Thank you so much for your help!

Stone Preston
Stone Preston
42,016 Points

try creating the array as a literal and see if that makes a difference:

NSMutableArray *lots =@[];
    lots[0] = @"bravo";
    lots[1] = @"lima";
Judy Tsai
Judy Tsai
6,376 Points

hmm..I tried that and it now gives me an additional error at declaration:

Unexpected '@' in program

Stone Preston
Stone Preston
42,016 Points

what version of xcode are you using?

literal array syntax and indexing arrays using [] was added to objective c relatively recently. so that might be your issue

Judy Tsai
Judy Tsai
6,376 Points

Hi, Stone,

You were correct, I tried the same code at home, which has a newer xcode and it worked fine!

Thank you for being patient and helpful for a newbie!