If self is able to store the base class instance then when we are returning the self, how it transformed to derived instance.
Here's what I think you're asking: suppose we have a base class Base and a subclass Derived. If -[Derived init] calls -[Base init] and -[Base init] returns a different instance, won't that different instance be an instance of Base and not Derived and thus inappropriate? For example, the new object won't have the instance variables that Derived might have added to the class.
The answer is that Base is not allowed to do that. If it replaces the original instance, it must do so in a manner that respects the dynamic type of that original instance. For example, it might do something like:
// Re-allocate with 100 extra bytes
id newSelf = NSAllocateObject([self class], 100, [self zone]);
[self release];
self = newSelf;
// ... continue to initialize ...
return self;
Or, it might dynamically generate a new subclass of the original class and then allocate a new instance of that new class.
NSString* newClassName = [NSString stringWithFormat:"%#_DynamicSubclass", NSStringFromClass([self class])];
Class newClass = objc_allocateClassPair([self class], [newClassName UTF8String], 0);
// ... further configure the new class, by adding instance variables or methods ...
objc_registerClassPair(newClass);
id newSelf = [newClass alloc];
[self release];
self = newSelf;
// ... continue to initialize ...
return self;
Whatever it does, it has to satisfy the constraint that the new instance is suitable to be used wherever the old instance was, based on its dynamic type.
self is a hidden method argument:
// this Objective-C
- (id) initWithString:(NSString*)str;
// gets implemented like this C function would be
- (objc_object*) Foo_initWithString(Foo* self, SEL _cmd, NSString* str);
It is a pointer to memory (allocated with alloc) that is already big enough to hold the most derived object. The most derived class calls super's init, which also calls its super's init and so each class in hierarchy gets its constructor called.
So, nothing is transformed — it is just a pointer to an already existing object, you can either return it (99.9% of the time) or substitute another object instead.
Note there is a second hidden argument, the selector _cmd, which in this case equals to #selector(initWithString:). You can also use it if you need current method name e.g. for debug logging.
Here super instance is not assigned to derived instance. self = [super init]; is simply like telling the runtime system to look for the init method to the super class method selector table... inside super -init method, the self is like support for both super class and derived class. In objective c, incase of class inheritance.. only instance variables are duplicated.. methods are shared by all classes in hierarchy. If u override.. u should do self = [super init]; this will lead u to NSObject -init method. If we override -init... methods from super class, make sure that the super -init... is called first. This is what i understand. Thank you.
Related
I read here (Is there a convention for naming initializer method in objective-c?) that "according to Apple, initializer methods should always begin with the word 'init'".
But, what is an initializer?
I know what is the "designated initializer". You could define it recursively: it is the only method calling the designated initializer of super ; plus: the designated initializer of NSObject is init.
But, what is an initializer?
I am asking this question because I hesitate between two names for an instance method of the class IceCream :
- (id)initIceCreamWithFlavour:
- (id)iceCreamWithFlavour: ("called on alloc")
I feel that relatively to the naming conventions of ARC, both names are OK. (This is my main concern here. Comments are welcome.) Now that I ask the question, the
solution (id)iceCreamWithFlavour: seems better.
But the question still holds: what is an initializer?
I would say: an initializer is a method you "call on alloc".
I would use - (id)initWithFlavour:.
So you would have:
IceCream *iceCream = [[IceCream alloc] initWithFlavour:Chocolate];
which tell you everything you need to know at a glance about the class and the initialisation parameter purpose. Restating ice cream in the method name is superfluous.
As for what the init method is, it's just the initialiser for the class. It's purpose is to create a configured new instance. To setup the default values (with, as in this case, some overrides or specific settings).
From your other method naming attempt, you could have:
+ (id)iceCreamWithFlavour:
Note the plus instead of minus, so this is a class method. This would be a suitable name for a convenience method which calls alloc] initWithFlavour: and returns the new instance.
Incidentally, if we add more parameters, don't restate with:
IceCream *iceCream = [[IceCream alloc] initWithFlavour:Chocolate sprinkles:YES];
Objective-C uses a 2 step creation process for objects.
The first step is memory allocation, and the second step is initialisation (which sets the initial state of an object):
MYIceCream* iceCream = [[MYIceCream alloc] initWithFlavor:#"Cherry"];
You can have multiple init methods for your classes, but you should have only one of them that sets the complete state for a new object. This is the designated initialiser (which usually takes the most parameters).
The MYIceCream class could have the following designated initialiser:
- (id)initWithFlavor:(NSString*)flavorName topping:(NSString*)toppingName
{
self = [super init];
if (self)
{
_flavorName = flavorName;
_toppingName = toppingName;
}
return self;
}
All other initialisers would just call the above method and provide defaults (or nil) for some parameters:
- (id)initWithFlavor:(NSString*)flavorName
{
return [self initWithFlavor:flavorName topping:kMYToppingChoclate];
}
You can also define methods, that combine allocation and initialisation. Those are called factory methods. They are defined as class methods (denoted with a + sign) and don't have an init prefix:
+ (id)iceCreamWithFlavor:(NSString*)flavorName;
The factory method would just call alloc and init in it's implementation:
+ (id)iceCreamWithFlavor:(NSString*)flavorName
{
return [[MYIceCream alloc] initWithName:flavorName];
}
Apple has a good intro to initialisers in the Cocoa Core Competencies guide and another good read in the Objective-C Programming Guide.
I would say: an initializer is a method you "call on alloc"
Thats partly true.
There are 3 types of "direct" initializers as far as i know :
[init] initializer (following [X alloc] call)
Initializers starting with "init" always follow an alloc call. I haven't seen any UIKit or Foundation Class being initialized like : [[NSArray alloc] arrayWithObject:] <- Does not exist like that.
Class - initializers
Class initializer create an object from a class scope without having called alloc before.
The implementation of this method, however, would sure call an [[alloc] init] to create an object.
Example : [NSMutableArray arrayWithCapacity:]
Class initializers always start with the corresponding class name.
In your case :
[IceCream iceCreamWithFlavor:]
Initializers creating from existing object.
These are creating an object from an existing one. They 'copy' the existing object and alter some properties.
Example:
UIColor *red = [UIColor redColor];
UIColor *thinRedColor = [red colorWithAlphaComponent:0.5];
They also start with their corresponding class name like the Class - initializers
If you look through the UIKit and Foundation classes, you will find that these patterns are used in every Class ( & Class - Cluster).
So to answer your question:
The "UIKit / Foundation" - way of naming your initializers would be :
When called after alloc:
- (instancetype)initWithFlavour:
When called on an existing object :
- (instancetype)iceCreamWithFlavourAlteredByValue:
When called on your Class-Object :
+ (instancetype)iceCreamWithFlavour:
An "initializer" is a "method in the init family" or "init method", for short.
"Method families" are defined in the "Clang/ARC documentation":
A selector is in a certain selector family if, ignoring any leading
underscores, the first component of the selector either consists
entirely of the name of the method family or it begins with that name
followed by a character other than a lowercase letter.
In addition:
init methods must be instance methods and must return an Objective-C pointer type.
So init and initWithFlavour: are "init methods", but iceCreamWithFlavour: or initialFoo are not.
A method can also explicitly marked as an init method:
-(id)myUnusualInitMethod __attribute__((objc_method_family( init )));
The Clang/ARC documentation also states what makes "init methods" special:
Methods in the init family implicitly consume their self parameter and return a retained object. Neither of these properties
can be altered through attributes.
A call to an init method with a receiver that is either self (possibly parenthesized or casted) or super is called a delegate
init call. It is an error for a delegate init call to be made except
from an init method, and excluding blocks within such methods.
As an exception to the usual rule, the variable self is mutable in an init method and has the usual semantics for a __strong
variable. ...
So in short
"Init methods" are the ones that are allowed allowed to call self = [super init];
or self = [self initWithSomeThing:],
to be an "init method", the method name has to start with "init".
On the other hand, the +[NSObject alloc] documentation states:
You must use an init... method to complete the initialization process.
and the -[NSObject init] documentation states:
In a custom implementation of this method, you must invoke super’s
designated initializer then initialize and return the new object.
which together means that alloc must be followed by a method from the "init family".
By convention you should use the - (instancetype)initIceCreamWithFlavour: method, and it should call the super init method (or as #Monolo points out below, it could call another init method such as initWithFlavour:size:).
The second one, you would make a class method + (instancetype)iceCreamWithFlavour: and it should allocate an instance and then call the initIceCreamWithFlavour method.
Assuming the class in this case is probably IceCream, I would actually rename the first one to just - (instancetype)initWithFlavour:
Note the usage of instancetype instead of id.
The class would look something like this:
+ (instancetype)iceCreamWithFlavour:(NSString*)flavour
{
return [[IceCream alloc] initWithFlavour:flavour];
}
- (instancetype)initWithFlavour:(NSString*)flavour
{
self = [super init];
if (!self) return nil;
// Initialize here
// do whatever you need to with the flavour parameter
return self;
}
I've read quite a few different posts about overriding the init method hoping to find answers for a couple of syntax questions I've been unable to figure out.
(id) init
{
self = [super init];
if(self){
}
return self;
}
So when we send the init method to the superclass of our subclass (let's assume superclass is NSObject) we are initializing all the instance variables inherited from the superclass? What else does this accomplish?
Whenever we create a new class, are we always inheriting instance variables from the parent class? For instance if I create a class called Fraction...
Fraction : NSObject
Fraction * myFrac = [[Fraction alloc] init]
Does the object that myFrac is referencing automatically inherit instance variables that I haven't even declared yet from the parent class?
Lastly when doing
self = [super init];
Aren't we initializing the superclass? What exactly are we storing in self? Is the result of init a pointer to our newly initialized object of our subclass?
I know this has been asked quite a few times, but I couldn't find these answers in the explanations. Sorry for the pileup of questions.
So when we send the init method to the superclass of our subclass
(let's assume superclass is NSObject) we are initializing all the
instance variables inherited from the superclass?
By default all ivars are set to nil/NULL/0/0.0/NO, depending on their type, yet your parent class may want to have them set to something else by default, in that case it will change their value in its init method.
What else does this accomplish?
Whatever NSObject (or your parent class) wants to do when a new object is initialized. Basically the convention says, you must not use an object that has not been initialized (with the exception of release - you may release an object that has never been initialized, that is explicitly allowed). Most other languages know the concept of contsructors, e.g. in Java you'd say new String(...) to create a string object, which does two things: It creates a new string object and it initializes the object by calling its constructor. Java will not allow you to do one thing without doing the other one. In Obj-C these two things are individual steps. alloc creates a new object and init initializes it. Offering two separate steps has advantages in some cases, but it also has the disadvantage that you must rely on conventions (init must be called before the object may be used, yet it must never be called more than once; the compiler will enforce neither one, though, at least not last time I checked that).
Whenever we create a new class, are we always inheriting instance variables from the parent class?
Yes; unless NSObject doesn't have any. Most ivars in Obj-C are private, protected is already a huge exception and you hardly ever see public ones. So basically you should never directly access the ivar of your parent class and thus you don't really have to care if you inherit any or none.
self = [super init];
Aren't we initializing the superclass? What exactly are we storing in
self? Is the result of init a pointer to our newly initialized
object of our subclass?
An init method is allowed to return a different object than the one the method has been called for. E.g. the following is valid:
static MyClass * ThereIsOnlyOneIstance;
- (id)init
{
if (ThereIsOnlyOneInstance) {
[self release];
return [ThereIsOnlyOneInstance retain]; // Without retain if using ARC
}
self = [super init];
if (!self) return nil;
ThereIsOnlyOneInstance = [self retain]; // Just `= self` if using ARC
return self;
}
The following two if-statements will be true:
MyClass a = [[MyClass alloc] init];
MyClass b = [MyClass alloc];
if (a != b) NSLog(#"a != b will be true");
b = [b init];
if (a == b) NSLog(#"Now a == b will be true");
Also an init method may fail, in which case it must release the object and return nil. So when calling [super init] this method may fail. Don't think too much about why it may fail, just keep in mind that it may fail. Now assume that you write the following code:
- (id)init
{
[super init]; // BAD!!! THIS IS BROKEN!!!
// Recent versions of CLANG will even make this
// a hard compiler error and refuse to compile that.
return self;
}
If [super init] failed, the object has been released and nil was returned, but you haven't updated self, you just return whatever value used to be in self prior to calling [super init]. As a result, you return a pointer to a dead object, since at the memory location self points to is no object any longer, this is a dangling pointer and using it can cause your app to crash or otherwise malfunction.
That's why you always must write the output of another init method back to self. Same is true for calling init from outside. The following code is broken:
MyClass x = [MyClass alloc];
[x init]; // BAD!!! THIS BROKEN!!!
It is broken, since init may release the object x points to, so x is now a dangling pointer. You always must capture the output of init back to the variable that should point to the object. The following code is correct:
MyClass x = [MyClass alloc];
x = [x init];
Though usually you alloc/init in just one combined call, of course:
MyClass x = [[MyClass alloc] init];
but that's actually the same, the compiler generated code will look no different than before.
So when we send the init method to the superclass of our subclass
(lets assume superclass is NSObject) we are initializing all the
instance variables inherited from the superclass? what else does this
accomplish?
No. The runtime initializes all variables in an Objective-C context to nil for you (rather than a garbage value without explicit initialization under the C and C++ runtimes). -init exists for setup, and it actually unnecessary for direct subclasses of NSObject, as the default -init method returns self and exits. That said, -init and those methods in its family are often necessary to initialize the member variables and setup state of objects further down the inheritance chain. Don't think of it as a companion to +alloc, rather just a handy setup method that's become the norm in the language.
Does the object that myFrac is referencing automatically inherit
instance variables that I haven't even declared yet from the parent
class?
If by "inherits" you mean that any variables you create still maintain the offset that their superclass hands them, then yes. If by "inherits" you mean "gives access to", then it depends. The #public, #private, and #protected directives determine the access rights a derived class gets to the instance variables of its parents.
Aren't we initializing the super class?
Yes, but understand that init and friends do not actually allocate memory, or setup anything language-specific. They just setup, hand off self, and walk away.
What exactly are we storing in self?
We're storing the object allocated by +alloc and returned to us by NSObject in the form of self. Calling through to super just gives the superclass an opportunity to run its setup, then pass us back a self pointer so we can do our setup.
Is the result of init a pointer to our newly initialized object of our subclass?
Oh, I sure hope so.
Is it safe to reinitialise self within a class method?
MyClass * a = [[MyClass alloc]init];
#implementation MyClass
{
-(id)init
{
if(self = [super init])
{
...
}
return self;
}
-(void)redefine
{
//??
self = [self init];
}
}
will a point to the reinitialized instance of MyClass?
Thank You,
nonono
Provided that (a) your class and its superclasses can be re-init'ed without leaking memory or resources and (b) you know that your class and its superclasses inits all return the self they are passed and not a reference to some other object, then yes...
Otherwise things will go wrong. Consider your redefine method; in the body of this method self is just a local variable whose contents is initialized to point to some object. Changing the value in that local variable does not change the object it originally pointed at, or the value of any other variables which point to that object. E.g. consider the variation:
#implementation Q
{
- (void) redefine
{
self = [[Q alloc] init]; // changes the *local* self to refer to a new object
}
...
}
...
Q *someQ = [[Q alloc] init]; // allocate an object
[someQ redefine]; // NO effect on someQ, another Q is just created and leaked
Clearly this does not alter someQ, and your version may not either. Your code will have the effect you wish if and only if you know init always returns the object it was passed - which is not guaranteed in Obj-C.
As long as init returns self, which it normally does, nothing will go wrong.
But you probably want to split your initialization to some separate method, which you can call from both init and redefine.
You need to return your new object from -init, not simply assign a new value to self. And you must remember to release the old self, since it was created with +alloc. Caveats aside though, returning a different object from -init is explicitly allowed. That's why you'll see newbies being corrected when they write something like this:
// Bad example! Do NOT do this!
Foo *foo = [Foo alloc];
[foo init];
This is an anti-pattern because -init is not required to return the same object it was called on. That means the above can end up assigning foo to point to an object that's been released, instead of to the object that was initialized in its place. This is why you always see +alloc and `init chained together like so:
Foo *foo = [[Foo alloc] init];
It's also why you need to reassign self when calling super's -init, because it may also have returned a different object.
self = [super init];
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 what it does. What does alloc return? what does init return?
Animal * k = [Animal alloc];
k = [k init];
alloc allocates a chunk of memory to hold the object, and returns the pointer.
MyClass* myObj = [MyClass alloc];
myObj cannot be used yet, because its internal state is not correctly setup. So, don't write a code like this.
init sets up the initial condition of the object and returns it. Note that what's returned by [a init] might be different from a. That explains the code Yannick wrote:
-init{
self=[super init]; // 1.
if(self){ // 2.
....
}
return self; // 3.
}
First, you need to call the superclass's init, to setup the superclass's instance variables, etc. That might return something not equal to the original self, so you need to assign what's returned to self.
If self is non-nil, it means the part controlled by the superclass is correctly initialized. Now you perform your initialization. All of the instance variables are set to nil (if it's object) and 0 if it's integer. You'll need to perform additional initial settings.
Return the set-up self. The returned self might be different from what's allocated! So, you need to assign the result of init to your variable.
This suggestions an important lesson: never split the call to alloc and init. Don't write:
MyClass* myObj = [MyClass alloc];
[myObj init];
because [myObj init] might return something else. Don't try to get around this by writing:
MyClass* myObj = [MyClass alloc];
myObj=[myObj init];
because you will eventually forget to write the part myObj= in the second line.
Always write:
MyClass* myObj = [[MyClass alloc] init];
I also don't recommend writing:
MyClass* myObj = [MyClass new];
because it does not correctly call the initialization method: some classes doesn't accept a plain init. For example, NSView needs initWithFrame:, which can't be called with new. So, don't use new either.
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;
}
alloc and init are two methods that are inherited from NSObject
you can provide your own methods or call the ones from NSObject
alloc allocates the memory to create a new instance of your class(#interface)
init initializes the contents of that instance, by default init sets all member values to 0/nil however you can create your own init method to customize what is done.
Animal * k = [[Animal alloc] init]; // creates a new Animal object
you can also write
Animal * k = [Animal new]; // which would be a bit more similar to other languages
The NSObject root class provides a class method, alloc,
alloc: reservers a memory location and returns the pointer to that memory location.
The alloc method has one other important task, which is to clear out the memory allocated for the object’s properties by setting them to zero.
This avoids the usual problem of memory containing garbage from whatever was stored before, but is
not enough to initialize an object completely.
You need to combine a call to alloc with a call to init, another NSObject method:
(id)init;
The init method is used by a class to make sure its properties have suitable initial values at creation.
The correct way to allocate and initialize an object is to nest the alloc call inside the call to init, like this:
ClassName *objectName = [ClassName alloc] init];
from: apple documents
Alloc will allocate the memory for the object, but Init puts the object into the memory and sets the default values.
Let's say I create my class and its init method. Why should I call and return value of superclass init assigned to self? Which cases it covers?
I would appreciate examples why would I need it for Cocoa superclass and non-Cocoa.
You mean why
self = [super init];
rather than
[super init];
Two reasons:
in initialisation, failure is indicated by returning nil. You need to know if initialisation of the super object failed.
the super class might choose to replace the self returned by +alloc with a different object. This is rare but happens most frequently with class clusters.
Edited in response to Michael's comment:
I can understand why I need to save and return [super init]. But is it just convention and good looking makes us use self as a temporary variable to pass result along?
No. Instance variables are accessed relative to the self pointer, so in the following:
-(id) init
{
self = [super init];
if (self != nil)
{
myBoolIvar = YES;
// The above is an implicit version of self->myBoolIvar = YES;
}
return self;
}
self has clearly got to point to the right block of memory i.e. the one you are going to return.
The other point is that if super init returns different class instance then the rest of the code after that line may not even make sense, lead to memory leaks and crashes, not even talking about the object instantiated from that class.
That could be a problem. If I subclassed NSNumber and [super init] decided to return an NSString (which it could - there's nothing to stop it) that would clearly be a disaster. Whatever super returns from -init must be "compatible" with the subclass in the sense of providing space for ivars and being further subclassible or it's a horrendous bug (unless, of course, the problem is documented). So, in general, you don't need to worry about checking the class. However, do read the documentation. See for instance the section on subclassing NSString in NSString's docs.
I know it is a little bit late for my answer, but I cannot stop myself from posting a link which I found very useful in clearing my doubt about this problem.
Matt Gallagher: What does it mean when you assign [super init] to self?
EDIT: As per the comments, here are the essential points in the link
To understand why self=[super init]; we need to consider many points. Let's tackle it one by one.
What is self
Every method has two hidden parameters: self and _cmd. So the method call
- (id)initWithString:(NSString *)aString
is changed by compiler into a function call like this
id initWithString(id self, SEL _cmd, NSString *aString);
Why do we need self?
The reality is that the compiler uses the self parameter to resolve any reference to an instance variable inside a method.
Suppose that we have a method setValueToZero and value is an instance variable of the class it belongs to, then the implementation
- (void)setValueToZero
{
value = 0;
}
will be converted by the compiler into a function like this
void setValueToZero(id self, SEL _cmd)
{
self->value = 0;
}
Do self already have a value when init is called?
Following is an example of a typical object creation and initialization.
[[MyClass alloc] initWithString:#"someString"]
Here, by the time we get into the initWithString method, self will have the newly allocated object as its value (i.e., the return value from [MyClass alloc]). In fact, it is almost guaranteed to be the correct, final value.
Why self = [super init];?
It is because [super init] is permitted to do one of the three things:
Return its own receiver (the self pointer doesn't change) with inherited instance values initialized.
Return a different object with inherited instance values initialized.
Return nil, indicating failure.
In the first case, assignment has no effect on self. In the third case, the initialization has failed, self is set to nil and it is returned.
The reason behind assignment to self is with the second case. Consider the following
- (id)initWithString:(NSString *)aString
{
self = [super init];
if (self)
{
instanceString = [aString retain];
}
return self;
}
We want the conversion from
instanceString = [aString retain];
to
self->instanceString = [aString retain];
to act on the correct value and thus we have to change the value of self.
When would [super init] return a different object?
In one of the following situations
Singleton object (always returns the singleton instead of any subsequent allocation)
Other unique objects ([NSNumber numberWithInteger:0] always returns the global "zero" object)
Class clusters substitute private subclasses when you initialize an instance of the superclass.
Classes which choose to reallocate the same (or compatible) class based on parameters passed into the initializer.
In all but the final case, continuing to initialize the returned object if it changes is a mistake — the returned object is already completely initialized and isn't necessary related to your class anymore. So a better init approach will be as follows
- (id)initWithString:(NSString *)aString
{
id result = [super init];
if (self == result)
{
instanceString = [aString retain];
}
return result;
}
Conclusion
You don't need to assign [super init] to self to make most classes work. In some obscure cases, it is actually the wrong thing to do.
So why do we continue to assign to self? It's the traditional template for an initializer, and although it's wrong in some cases, it is right in other cases which have been written to expect this approach.
Basically every Objective-C class is a subclass. It's either some class you've specified or NSObject.
In the subclass (your class that you're working on) you call
self = [super init]
What this basically does is calls the super class's (the ones I mentioned above) init method (the constructor) and assigns it to the current class.
This makes sure that the superclasses' initializing method is called.
Now for
If(self)
This basically checks if the above piece of code worked.
This is done to insure that if you call some Instance Variable of the super class, you'll be able to do so.
In most cases, setting self to [super init] does nothing since [super init] will wind up returning self anyway. There are some rare cases, however, where [super init] will return something different. It may return nil if it fails to initialize the superclass for some reason or it may decide to return a completely different object.
Source
Implementing The Designated Initializer
**
self
**
Inside a method, self is an implicit local variable. There is no need to declare it, and it is automatically set to point to the object that was sent the message. (Something like this in Android programming.) Typically, self is used that an object can send a message to itself. Example here:
return self;
**
super
**
When we overriding a method, we want to keep what method of the superclass is doing and have your subclass add something new on that. To make it easier, there is compiler directive in Objective-C called super.
How does super work? Usually when you send a message to an object, the search for a method of that name starts in the object's class. If there is no such method, the search continues in the superclass of the object. The search will continue up the inheritance hierarchy until a suitable method is found. (If it gets to the top of the hierarchy and no method is found, an exception is thrown).
When we send a message to super, we are sending message to self, but the search for the method skips the object's class and start at the superclass. In the above case, we send init message to super. This calls NSObject's init method.
Because you have to initialize the object somehow, and presumably you want to do any initialization a superclass required be done, since you're descending from it.