Objective-C:init 方法应该在 .h 中声明吗?
首先,据我了解,Objective-C中的init在功能上类似于Java中的构造函数,因为它用于初始化实例变量并准备类做一些工作。这是正确的吗?
我知道 NSObject
实现了 init
,因此不需要在任何 .h
文件中声明。
但是给定类的 init 的自定义实现怎么样,例如:
(id) initWithName:(NSString *) name
这样的声明应该作为 .h
的一部分列出,还是没有必要?是按照惯例还是有其他原因?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,如果您希望能够调用此个性化初始化方法(
initWithName
),则必须声明它。在该方法中您首先要做的就是调用[super init];
。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];
.init
与 Java/C++ 中的构造函数完全不同。构造函数总是在创建对象时执行。但是init
的执行取决于你。如果您在alloc
之后不发送init
消息,那么它将不会执行。如果您从
NSObject
派生,这将毫无问题,因为NSObject
的init
不执行任何操作。你不需要在头文件中添加
init
,因为它继承自NSObject
,但你需要在头文件中添加自定义的init方法(不是继承的) 。请注意,init
方法只是具有命名约定的普通方法,但从技术上讲与其他方法没有区别。如果您没有在头文件中指定自定义 init 方法,而是将该消息发送到对象,则编译器将生成警告。不会出现编译错误。因此,如果您决定忽略该警告,那么您也可以从标题中省略该警告。但如果该方法没有实际实现,您将会遇到运行时崩溃。所以最好将所有未继承的方法都添加到头文件中。
init
is by no means similar to constructor in Java/C++. The constructor always executes when the object is created. But the execution ofinit
is up to you. If you don't sendinit
message afteralloc
then it will not execute.And this will work without any problems if you derive from
NSObject
, asinit
ofNSObject
does nothing.You do not need to add
init
in the header file, because it is inherited fromNSObject
but you need to add custom init methods (that are not inherited) to the header file. Note thatinit
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.