Instantiating Objects
Once you've created your interface and implementation files, you can create and manipulate instances very easily. The easiest way to create an instance is to send the class a new method:
#include <MyClass.h> ... MyClass *myInstance = [MyClass new];
However, this is most likely not what you would see in Objective-C code (but for the sake of simplicity, you will see it in the example application). Instead, the correct way to instantiate objects is to send the class an alloc method, which returns an allocatedbut uninitializedinstance of the class, and then send that method an appropriate initializer message. All initializer methods should return the instance itself or nil on failure.
id myInstance = [[MyClass alloc] init];
This two-phased instance construction makes the division between constructing and initializing very clear, and you will often see things like:
id myInstance = [[MyClass alloc] initWithFoo:foo andBar:bar];
This could hardly be any clearer. What happens if the alloc fails? It will return nil, and the init: message will be sent to the nil object, which ignores any message it receives and returns nil also.
CUJ