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) Beyond the Basics Alloc and Init

Ricky Su
Ricky Su
2,415 Points

What does init do when it doesn't put any real data to initialize the allocated memory?

I understand initWithInt will put Integer number to the memory, but what if init without any value or data?

For example, NSNumber *n = [[NSNumber alloc] init]

Is init a must here?

1 Answer

Stone Preston
Stone Preston
42,016 Points

if you just use

NSNumber *n = [[NSNumber alloc] init]

n would be a properly allocated and initialized object, however its value is simply null

if you use

NSNumber *n = [[NSNumber alloc] initWithInt:2];

n would be a properly allocated and initialized object, and its value would be 2.

calling init is always a must after alloc (the init method what returns the object, sets up default values, etc) . alloc only allocates the chunk of memory to be used. Its good practice to always call alloc and init together