Domanda

In Cocoa, for NSObjects, shouldn't both init and initialize be class methods?

È stato utile?

Soluzione

+initialize can be overridden (it's optional) to perform class-wide initialization. -init performs initialization of a single instance of a class, though it's often refined by adding arguments in classes derived from NSObject (ex: UIView's initWithFrame: method).

Since -init initializes a single instance (in particular, it has access to the instance's variables), it can't be a class method.

Altri suggerimenti

From the docs:

The runtime sends initialize to each class in a program just before the class, or any class that inherits from it, is sent its first message from within the program.

This means that the first time you send a message to the class, whether it be alloc or some defined class method, initialize is called first, once, for the entire run of the application. As opposed to load, it is possible to include a class in a project and never hit initialize.

init, on the other hand, is

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

Meaning, init is sheerly used for initializing class instances.

Edit --

Following the edited question, alloc creates the instance while init initializes it, which is why alloc is a class method and init is an instance method.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top