Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
498 views
in Technique[技术] by (71.8m points)

initialization - Objective-C: init vs 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...