May 27, 2014

Fast food objective-c (part 3) : Creating Objects

Creating Objects

There are two main ways to create an object. The first is the one you saw before:
NSString* myString = [NSString string];
This is the more convenient automatic style. In this case, you are creating an autoreleased object, which we'll look at in more detail later. In many cases, though, you need to create an object using the manual style:
NSString* myString = [[NSString alloc] init];

This is a nested method call. The first is the alloc method called on NSString itself. This is a relatively low-level call which reserves memory and instantiates an object. 
The second piece is a call to init on the new object. The init implementation usually does basic setup, such as creating instance variables. The details of that are unknown to you as a client of the class. 
In some cases, you may use a different version of init which takes input:
NSNumber* value = [[NSNumber alloc] initWithFloat:1.0];

No comments:

Post a Comment