Do you need to declare 'init' in the header file?


#1

This seems like a simple question, but I can’t find an answer anywhere.

If you create a custom init method, do you need to declare it in the header file?

For my BNRContainer class, I’ve created the subitems array in init:

[code]- (id)init
{
self = [super init];

if (self)
{
    subitems = [[NSMutableArray alloc] init];
}

return self;

}[/code]

I haven’t declared my init method in BNRContainer.h. XCode doesn’t seem to care. Is that bad practice? Should I add it? Is there a better place to initialise the array?

I can see that if you add something like initContainerWithArrayOfItems or initContainerWithSpecialMethodNobodyElseKnowsAbout or whatever then the compiler needs to be told. But what about plain init? Could it ignore my method and go straight to the NSObject init?

Thanks in advance a) for any help and b) to the authors, for (based on the first few chapters) an excellent and enjoyable book.

Best wishes,

James


#2

The init method is already declared by the parent class. What you’re doing is overriding it for the subclass, so in that case you don’t need to include it in the header. If you were creating a unique initializer (or any unique instance method), you do want to include those in your header file.


#3

Thank you – that makes sense. I couldn’t find anything else online or in the XCode documentation that made that clear!


#4

I believe it does mention this in the book on Chp 2. :slight_smile: