Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS

Alex Taylor
Alex Taylor
2,758 Points

When to use alloc and init

Hi All,

I've just been going through the exercises in the foundation framework section of objective C Basics and I have a question about the 'for' loop.

e.g. for (NSString *string in foo) {NSLog(@"%@", string);}

Why don't we need to alloc and init the variable declared NSString *string? As isn't it still an instance of the NSString object that will be holding a value and hence requiring space to allocated and initialised?

Any help would be greatly appreciated, Thanks, Alex

Mårten Björk
Mårten Björk
3,776 Points

+1. Just took this course and this could definitely be explained in more detail.

3 Answers

Chris McKnight
Chris McKnight
11,045 Points

NSString *string is actually just a pointer to an object in the heap and pointers are designated by the *. You can think of a pointer as a note on a classroom door that says Go to classroom 131. In the case of fast enumeration (for in), you are going through an array that contains pointers to objects in the heap, so, you don't need to alloc and init them. The objects already exist in the heap and can't be nil since nil is not allowed in an array; nil is used to mark the end of the array. Remember, an array contains pointers to objects of unknown type id.

You want to alloc and init when and object doesn't exist in the heap. The objects get allocated (space is created for the object) and the object gets setup and you get a pointer to the object back.

Hope this makes sense

Stone Preston
Stone Preston
42,016 Points

You can also read yesterday's thread that discussed this topic)

Alex Taylor
Alex Taylor
2,758 Points

Excellent, thank you both, that is much clearer to me now, Alex