Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 561
jrdioko Avatar asked May 31 '11 17:05

jrdioko


People also ask

What is static in Objective-C?

In both C and Objective-C, a static variable is a variable that is allocated for the entire lifetime of a program. This is in contrast to automatic variables, whose lifetime exists during a single function call; and dynamically-allocated variables like objects, which can be released from memory when no longer used.

How do I create an NSArray in Objective-C?

Creating NSArray Objects Using Array Literals In addition to the provided initializers, such as initWithObjects: , you can create an NSArray object using an array literal. In Objective-C, the compiler generates code that makes an underlying call to the init(objects:count:) method.

How do I initialize a class in Objective-C?

Test example = [[Test alloc] init]; example.name = @"s"; you can write something like this: Test example = [[Test alloc] initWithName:@"s"]; Please note that this is very common for initialization method to return newly created object, hence the initialization method usually returns 'id' type (not void).

What is init in Objective-C?

init() Implemented by subclasses to initialize a new object (the receiver) immediately after memory for it has been allocated.


2 Answers

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

like image 56
Caleb Avatar answered Dec 09 '22 19:12

Caleb


To draw a parallel for Java developers, init is like a constructor, while initialize is like a static block on a class.

like image 29
Eki Avatar answered Dec 09 '22 19:12

Eki