Objective-C: init vs initialize

In Objective-C, what is the difference between the init method (i.e., the designated initializer for the class) and the initialize method? What initialization code should be placed in each?

+71
initialization objective-c initializer init
May 31 '11 at 17:52
source share
2 answers

-init is an instance method used to initialize a specific object. +initialize is a class method that runs before any instances of the class are created and before other class methods are run. +initialize is not something you use most of the time, but it is useful for setting up any static variables that the class as a whole can use, or for ensuring certain conditions are met before any instances are created.

The code belonging to the -init method is described in detail in the section Implementing an Initializer Objective-C Programming Language . Class initialization is also discussed (i.e. +initialize ) and why you might need to do this in the same document in the Class Objects section, The code that comes in +initialize is usually heavily tied to the special functionality of the class, which requires that You initialized it first. One important thing to consider in +initialize (and in any class method) is that self in a class method refers to the class itself, and not to an instance of the class.

+123
May 31 '11 at 17:55
source share

To draw a parallel for Java developers, init is like a constructor, and initialization is like a static block for a class.

+16
Mar 23 '13 at 9:06 on
source share



All Articles