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 trialLuis Paulino
Courses Plus Student 1,779 PointsHow do I allocate and int the NSString?
NSString *myRide =[[NSString *myRide alloc]; this is my attempt. What exactly am I doing wrong?
1 Answer
Martin Wildfeuer
Courses Plus Student 11,071 PointsThe concept of creating (initializing) an instance (object) of a class looks as follows:
// Standard initialization
// Allocate memory first, than initialize the object
AClass *myInstance = [[AClass alloc] init];
// Most objects provide a shorthand method
// that is equivalent. Note: some classes have
// more descriptive shorthand initializers, like
// `array` instead of new `for` NSArrays.
AClass *myInstance = [AClass new];
Please note that this might not be the designated initializer, many times you want to pass parameters to the initializer. Code completion and docs to the rescue ;)
Applying that to your task, it might look like this:
NSString *myRide = [[NSString alloc] initWithString:@"Porsche"];
However, code completion will warn you that this way of initializing a string is redundant. NSStrings can be initialized with so called literals
:
NSString *myRide = @"Porsche";
There is many ways of initializing objects, so it is always worth checking the class documentation what might come in handy for your case.
Hope that helps :)