4

Recently i was told Apple is discouraging the use of new, and google's iOS coding standards also has this to say:

Do not invoke the NSObject class method new, nor override it in a subclass. Instead, use alloc and init methods to instantiate retained objects. Modern Objective-C code explicitly calls alloc and an init method to create and retain an object. As the new class method is rarely used, it makes reviewing code for correct memory management more difficult.

Why would it make reviewing code for correct memory management more difficult though?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
jfisk
  • 6,125
  • 20
  • 77
  • 113
  • 3
    "As the new class method is rarely used" -- People aren't expecting it. – Kevin Jul 31 '13 at 18:28
  • I don't like `new` because it hides an `alloc`+`init`... You don't get it immediately and may forget to release your object and so creating some issues... That's what says the quote. – Larme Jul 31 '13 at 18:32
  • @Larme: You don't get what immediately? – jscs Jul 31 '13 at 18:33
  • You may don't get (I mean remember) the `alloc`+`init` since both methods are hidden by the `new`. It's just an habit to have, but since I develop for iOS, I don't remember having seen a `new` instead of a `alloc`+`init` in code. In other words, `new` is not very explicit for calling the two methods hidden. – Larme Jul 31 '13 at 18:36
  • 2
    possible duplicate of [Use of alloc/init instead of new](http://stackoverflow.com/q/719877), [Alloc init and new in ObjC](http://stackoverflow.com/q/3330963), [Why are alloc and init called separately in ObjC?](http://stackoverflow.com/q/1385410) – jscs Jul 31 '13 at 18:36

1 Answers1

4

I expect the reference to ease of code reviews merely meant that human readers of your code may not notice the word 'new' as their eyes scan over the code looking for alloc-init calls.

In Objective-C, the word 'new' is a shortcut for calling alloc and init. But then you cannot pass arguments; you are calling the no-arg constructor. If you later change your code in such a way that you now want to call one of the other constructors and pass arguments, you will need to change your "new" to an alloc-init. This is common enough that it is yet anothe reason to avoid calling 'new' in the first place.

There is no advantage to calling 'new' over calling alloc-init. The 'new' word is only in Objective-C because other languages such as Java use that keyword.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154