Object creation:
An object comes into runtime existence through a two-step process that allocates memory for the object and sets its state to reasonable initial values. to allocate an Objective-C object, send an alloc or allocWithZone: message to the object's class. the runtime allocates memory for the object and returns a "raw" (uninitialized) instance of the class. it also sets a pointer (known as the isa pointer) to the object's class, zeros out all instance variables to appropriately typed values, and sets the object's retain count to 1.
After you allocate an object, you must initialize it. initialization sets the instance variables of an object to reasonable initial values. it can also allocate and prepare other global resources needed by the object. you initialize an object by invoking an init method or some other method whose name begins with init. these initializer methods often have one or more parameters that enable you to specify beginning values of an object's instance variables. if these methods succeed in initializing an object, they return it; otherwise, they return nil. if an object's class does not implement an initializer, the Objective-C runtime invokes the initializer of the nearest ancestor instead.
It means that two steps 1 are required to allocate memory 2 for initialization to create an object.
1. allocate memory. sent alloc orallocWithZone: message to the object's class. This is the common [Class alloc]. Or the uncommon [Class allocWithZone].
2 initialization. You need to call the init Method for initialization. All kinds of init methods that require or do not have parameters are counted.
In the above object creation method, the return value must be sent to the Automatic Object Management pool.
IOS interview example: Write an NSString class implementation
+ (Id) initWithCString :( const char *) nullTerminatedCString encoding :( NSStringEncoding) encoding;
+ (Id) stringWithCString: (const char *) nullTerminatedCString
Encoding: (NSStringEncoding) encoding
{
NSString * obj;
Obj = [self allocWithZone: nsdefamalmalloczone ()];
Obj = [obj initWithCString: nullTerminatedCString encoding: encoding];
Return AUTORELEASE (obj );
}
The Form of an Object-Creation Expression
A convention in Cocoa programming is to nest the allocation call inside the initialization call.
MyCustomClass * myObject = [[MyCustomClass alloc] init];
Convenience function: refers to the factory method without user management.
+ (Id) dataWithContentsOfURL :( NSURL *) url;