Objective-C: Should init methods be declared in .h?

你说的曾经没有我的故事 提交于 2019-12-12 10:30:32

问题


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?


回答1:


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.




回答2:


Yes you have to declare it if you want to be able to call this personalized initialisation method (initWithName). And the first think you have to do in that method is to call [super init];.



来源:https://stackoverflow.com/questions/6749628/objective-c-should-init-methods-be-declared-in-h

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!