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 Object-Oriented Objective-C Memory, Arrays and Loops, Oh My! Alloc and Init

Girish P
Girish P
276 Points

I didn't get this question, alloc means to allocate the memory and what about init it??

Please reply if anyone knows the answer

My question was --> Create an NSString variable called 'myRide' and allocate and init it, but don't give it a value yet.

variable_assignment.mm
NSMutableDictionary * carDict = [[NSMutableDictionary alloc]initWithObjectsAndKeys: @"Honda",@"Make",@"Accord",@"Model",nil];
NSString * myRide ;

1 Answer

Andrew Shook
Andrew Shook
31,709 Points

Not an Objective C expert, I'm much more experienced with Swift, but form what I understand alloc and init are both methods of NSObject and all Objective C classes extend from NSObject. Alloc returns a pointer to the memory location of the object. Notice the "*" that is always put after the type in an alloc call.

variable_assignment.mm
NSMutableDictionary * carDict = [[NSMutableDictionary alloc]initWithObjectsAndKeys: @"Honda",@"Make",@"Accord",@"Model",nil];

That's the pointer part. When alloc is run the program makes a blank copy of the object, assigns it a space in memory, and then returns a pointer of type id. The id type is, for lack of wanting to get to in depth here, a generic object pointer. The important thing to note about alloc, is that you can not use the it's return without calling init. Basically, all alloc has done is created you a blank object with no state, and in order to give that object state you call one of it's init methods. The init methods of an object are what actually return you the fully functional object (actually init returns a a pointer as well the, but this pointer now points to) . It's important to note that alloc and init may not always return a pointer to the same thing.

Girish P
Girish P
276 Points

Thanks buddy :)