Objective-C:初始化与初始化 [英] Objective-C: init vs initialize

查看:124
本文介绍了Objective-C:初始化与初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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.

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屋!

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