Can someone explain to me what init and alloc do in Obj-C. I am reading this obj-c book that gives an example of creating object but it does not really go into details of wh
In its simplest form:
alloc: short for allocation, reservers a memory location and returns the pointer to that memory location. This pointer is then stored in the k variable.
init: short for initialization, sets up the object and returns the object. The init method depends on the object, but it generally involves sending the init message to the superclass. And if that init method (of the superclass) returns an object (not nil) some ivars may be set up depending on the task of that class.
--
Example of an init implementation, the Schedule class initializes its channels ivar with an empty array. Basically your giving the Schedule object a chance to sort itself out, so it can start receiving messages once it is created. You could remove the channels initialization from the init method, but then you would have to check if the channels ivar is nil in every method of the Schedule class and initialize it if it is indeed nil.
- (Schedule*)init {
self = [super init];
if (self) {
channels = [[NSMutableArray alloc] initWithCapacity:0];
}
return self;
}