Objective-C:init 方法应该在 .h 中声明吗?

发布于 2024-11-24 22:00:51 字数 325 浏览 1 评论 0原文

首先,据我了解,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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

池予 2024-12-01 22:00:52

是的,如果您希望能够调用此个性化初始化方法(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];.

堇色安年 2024-12-01 22:00:51

init 与 Java/C++ 中的构造函数完全不同。构造函数总是在创建对象时执行。但是init的执行取决于你。如果您在 alloc 之后不发送 init 消息,那么它将不会执行。

// init does not execute here
MyObject *obj = [MyObject alloc];

如果您从 NSObject 派生,这将毫无问题,因为 NSObjectinit 不执行任何操作。

你不需要在头文件中添加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 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文