For me who had been using the C # language before, I was confused when I first approached Objective-c to create an object, and why would I create an object in general, by sending two messages (calling two methods) to create a class instance object (for example [[[UIButton alloc] init])? Believe that the use of Java will also have this feeling, give a type call initialization method is not finished? That's a problem! Although new one step is also used in objective-c (for example: [UIButton new]), this usage seems to be less common. Fruit companies must be justified in doing so. Let's start with a discussion of the pros and cons of using a direct creation approach.
As mentioned above, we can create an object by [UIButton new], which essentially calls [[UIButton alloc] init] inside the message. Indicates that objects created by new are allocated memory from the heap in the default alloc manner. The result, of course, is that it is possible to create an object correctly, but it also kills other ways of allocating memory in the C language. Consider this scenario, which assumes that the ability to share special memory between processes or to map memory to the virtual address space of a computer to store pictures instead of allocating them in memory by default is not appropriate. Perhaps you will say that I can create the following two methods:
+ (Instancetype) imagewithvirtualmemory: (Virtualmemory *) memory; + (Instancetype) imagewithsharedmemory: (Sharedmemory *) memory;
Of course, the virtuamemory and sharedmemory in the code are virtual two classes. We don't have to pay too much attention.
This seems to solve the problem, but this is just two variations of the distribution pattern, and the Init method can have multiple variations, if a class now has 5 alloc ways, and 8 init modes. If you combine the creation of objects in a single method, this means that we need to create a way to create 5*8=40 objects. Introduced here, I believe we have a reason to take the two-stage creation approach.
Why does the COCOA framework use a two-phase approach to creating objects?