Objective-C:应该在.h中声明init方法吗? [英] Objective-C: Should init methods be declared in .h?

查看:80
本文介绍了Objective-C:应该在.h中声明init方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,据我了解,Objective-C中的init在功能上类似于Java中的构造函数,因为它用于初始化实例变量并准备一个类来做一些工作.这是正确的吗?

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?

我知道NSObject实现了init,因此不需要在任何.h文件中声明它.

I understand that NSObject implements init and as such it does not need to be declared in any .h files.

但是对于给定类的init的自定义实现如何呢?例如:

But how about custom implementation of init for a given class, for example:

(id) initWithName:(NSString *) name

应该将这样的声明列为.h的一部分,还是没有必要?是按照惯例完成的还是有其他推理?

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?

推荐答案

init绝不同于Java/C ++中的构造函数.构造函数总是在创建对象时执行.但是init的执行取决于您.如果您没有在alloc之后发送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];

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

And this will work without any problems if you derive from NSObject, as init of NSObject does nothing.

您不需要在头文件中添加init,因为它是从NSObject继承的,但是您需要在头文件中添加自定义的init方法(不继承).请注意,init方法只是具有命名约定的普通方法,但是从技术上讲,它与其他方法没有什么区别.

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.

如果您没有在头文件中指定自定义init方法,而是将该消息发送给对象,则编译器将生成警告.不会有编译错误.因此,如果您决定忽略该警告,则也可以从标题中忽略该警告.但是,如果未实际实现该方法,则将导致运行时崩溃.因此,最好添加所有未在头文件中继承的方法.

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.

这篇关于Objective-C:应该在.h中声明init方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆