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 NSNumber

Can you help me understand the breakdown of this code?

Mainly, what I want to know is why the second line is written the way it's written and what the terms alloc and init mean.

NSNumber *mike;
mike = [[NSNumber alloc] initWithInt:23];
NSLog(@"mike's number is %@", mike);

1 Answer

Stone Preston
Stone Preston
42,016 Points

all objects in objective c are pointers, thats why you had to use the asterix before the obejcts name when you declared it here:

NSNumber *mike;

one of the advantages of using pointers with objects is that when you reference an object you arent referencing the object itself, but the memory address of the object. The memory address is tiny compared to the actual object, which makes it easy to pass around in your code.

NSNumbers are objects. objects must be allocated and initialized before they can be used. you can think of allocating and initializing objects as "creating them". allocation sets aside the memory for your object and init sets up your object. in this case you use

mike = [[NSNumber alloc] initWithInt:23];

which allocates memory for an NSNumber object, initializes it with the value 23, and returns the object. this object is assigned to the pointer mike. you can have multiple initializer methods for an object, NSNumber has many such as initWithFloat, initWithInt etc etc.you can even create custom initializer methods to customize the way your objects are set up when they are first created.

All objects are not actually pointers, but you create a pointer that points to the object that is allocated in heap. Anything that you use alloc to create is placed in the heap, so you need a pointer to reference it.