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

Dynamic Typing Challenge 2

I have got through the first challenge on Dynamic Typing on Objective C basics but I just can't pass challenge 2.

The questions is:

Assign an NSNumber literal with a value of '4' to the variable 'thing'.

I have watched the video over and over and can't get this answer anywhere?

I think the closest I have got is this but it still fails:

id thing = [[NSNumber alloc] initWithInt:4];

Probably way off

Can anyone help?

5 Answers

Amit Bijlani
STAFF
Amit Bijlani
Treehouse Guest Teacher

Your answer is sort of correct but you should not replace what you did in task 1. Simply add to it.

Task 1

id thing = nil;

Task 2

id thing = nil;
thing =  [[NSNumber alloc] initWithInt:4];

Thanks for the answer. Why doesn't this work?

id thing = nil;

NSNumber *thing = @4;

is it because thing has not been instantiated until the alloc and initWithInt methods are called?

Amit Bijlani
Amit Bijlani
Treehouse Guest Teacher

You cannot declare a variable with the same name twice. With id thing = nil; you are declaring that there is a new variable named thing that is initialized to nil. On the second line, once again you are declaring a new variable thing that is of type NSNumber initialized to an object containing number 4.

You can do this:

id thing = nil;
thing =   @4;

I was doing the same mistake, it's nice to know that if adding the NSNumber before the variable name 'thing' you are declaring a new variable instead of assigning a value to the existing one.

also there is a convenience constructor that will pass as well...

thing = [NSNumber numberWithInt:4];

Thanks Amit,

I had kept task 1 in place but I used id at the start of task 2 also so by removing it, it worked!

Thanks again.

Douglas Rogers your way is the best way to do this in my opinion.

thing = [NSNumber numberWithInt:4];