Allocating and Initializing Objects
The messages shown in this hour have demonstrated how you can allocate and initialize objects. Because these processes are used so extensively in Objective-C, it is worthwhile to take a few moments to look more carefully at these messages.
As noted previously, you most often create instances of classes by calling alloc. This is a class method of NSObject, which means it is available to any class in the frameworks or in your own code. You simply send a message to the class, and you get back a new instance.
MyClass*newInstance = [MyClass alloc];
Immediately thereafter, you initialize the newly created instance, most often with a call to init or a related method.
newInstance = [newInstance
As noted previously, you can combine these two messages into one line of code.
MyClass*newInstance = [[MyClass alloc] init];
It makes sense that alloc returns an object that you can place in an instance variable. You might be surprised that init also returns an object. The reason for this is that after you have created the new object, the call to init might not only set instance variables and other settings, but it also might decide to replace the allocated object with another one. That is the one that you should use thereafter.
By convention, initializer names start with init. They might have additional parameters, such as these various initializers for UIBarButtonItem in Cocoa Touch:
– initWithBarButtonSystemItem:target:action: – initWithCustomView: – initWithImage:style:target:action: – initWithTitle:style:target:action: – initWithImage:landscapeImagePhone:style:target:action:
Initializers may set various properties of the object being created; they also may take various routes to complete the initialization. If you create a series of initializers, there are two rules to follow:
- The first step in an initializer is to call [super init]. This ensures that the basic object is there and complete.
- Initializers can call other initializers that each performs some initialization. The most complete initializer (that is, the one that sets all of the properties rather than just some of them) is the designated initializer. The others are secondary initializers.
It is a good practice to put all of the initializers together in your code, possibly using a #pragma mark – section. This separates the initializers and, in the list of methods in the jump bar for a file, the pragma section names will appear.