First of all, as I understand it, init in Objective-C
, functionally is similar to a constructor in Java
, as it is used to initialize instance variables and prepare a class to do some work. Is this correct?
I understand that NSObject
implements init
and as such it does not need to be declared in any .h
files.
But how about custom implementation of init for a given class, for example:
(id) initWithName:(NSString *) name
Should declaration like this be listed as part of .h
, or it is not necessary? Is it done by convention or is there any other reasoning?
init
is by no means similar to constructor in Java/C++. The constructor always executes when the object is created. But the execution of init
is up to you. If you don't send init
message after alloc
then it will not execute.
// init does not execute here
MyObject *obj = [MyObject alloc];
And this will work without any problems if you derive from NSObject
, as init
of NSObject
does nothing.
You do not need to add init
in the header file, because it is inherited from NSObject
but you need to add custom init methods (that are not inherited) to the header file. Note that init
methods are just normal methods with a naming convention, but technically there is no difference from other methods.
If you do not specify your custom init methods in the header file, but send that message to an object, the compiler will generate a warning. There will be no compile error. So if you decide to ignore the warning then you can omit that from header too. But you will get a runtime crash if the method is not actually implemented. So it's better to add all methods that are not inherited in header file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With