Should I avoid using the new to initialize my objects?

Recently I was told that Apple does not encourage the use of new ones, and google iOS coding standards also say the following:

Do not reference the method of the NSObject new class or override it in a subclass. Instead, use the alloc and init methods to instantiate stored objects. Modern Objective-C code explicitly calls alloc and the init method to create and save an object. Since the method of the new class is rarely used, it makes it difficult to analyze the code for proper memory management.

Why would he make code analysis difficult to manage memory properly?

+4
source share
1 answer

I expect that a link to the simplicity of code reviews simply means that readers of your code may not notice the word β€œnew” as their eyes scan code looking for alloc-init calls.

In Objective-C, the word "new" is a shortcut to invoke alloc and init. But then you cannot pass arguments; you call the no-arg constructor. If you later change your code so that now you want to call one of the other constructors and pass arguments, you will need to change your "new" to alloc-init. It is common enough that this is another reason to avoid calling the β€œnew” in the first place.

There is no advantage to calling the β€œnew” call to alloc-init. The "new" word is found only in Objective-C, because other languages, such as Java, use this keyword.

+4
source

Source: https://habr.com/ru/post/1494555/


All Articles