Objective-C:初始化与初始化 [英] Objective-C: init vs initialize
问题描述
在Objective-C中,init
方法(即类的指定初始化程序)和initialize
方法之间有什么区别?每个中应放置什么初始化代码?
In Objective-C, what is the difference between the init
method (i.e. the designated initializer for a class) and the initialize
method? What initialization code should be put in each?
推荐答案
-init
是一个实例方法,用于初始化特定对象. +initialize
是一个类方法,在创建该类的任何实例之前以及在运行其他类方法之前运行. +initialize
通常不是您经常使用的东西,但是它对于设置整个类可以使用的任何静态变量或确保在创建任何实例之前确保满足某些条件非常有用.
-init
is an instance method, used to initialize a particular object. +initialize
is a class method, run before any instances of the class are created and before other class methods are run. +initialize
isn't something you use most of the time, but it's handy for setting up any static variables that the class as a whole might use, or for ensuring that certain conditions are met before any instances are created.
Objective-C编程语言.还讨论了初始化类(即+initialize
)以及为什么可能需要在同一文档中的
The code that belongs in an -init
method is described thoroughly in the Implementing an Initializer section of The Objective-C Programming Language. There's also some discussion of initializing classes (i.e. +initialize
) and why you might need to do that in the same document, in the Class Objects section. The code that goes into +initialize
will generally be strongly tied to the special functionality of the class that requires you to initialize it in the first place. One important thing to keep in mind in +initialize
(and in any class method) is that self
in a class method refers to the class itself, not an instance of the class.
这篇关于Objective-C:初始化与初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!