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?
initis by no means similar to constructor in Java/C++. The constructor always executes when the object is created. But the execution ofinitis up to you. If you don’t sendinitmessage afterallocthen it will not execute.And this will work without any problems if you derive from
NSObject, asinitofNSObjectdoes nothing.You do not need to add
initin the header file, because it is inherited fromNSObjectbut you need to add custom init methods (that are not inherited) to the header file. Note thatinitmethods 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.