Why are you using the class method constructor compared to alloc / init?

Objective C / Cocoa has two options for constructors:

1. Class constructor

Product *product = [Product productWithIdentifier:@"Chocolate"]; // Use product 

2. Alloc / init Constructor

 Product *product = [[Product alloc] initWithIdentifier:@"Chocolate"]; // Use product [product release]; 

What am I doing

  • I usually use the class method only because it looks cleaner and you don't need a release.
  • I see a lot of alloc / init - what advantage does this do?

My question

  • Which one is preferable? Or is it just a matter of taste?

the code

For context, the Product class will have the following:

 +(Product *)productWithIdentifier:(NSString *)identifier_ { return [[[[self class] alloc] initWithIdentifier:identifier] autorelease]; } -(Product *)initWithIndentifier:(NSString *)identifier_ { self = [super init] if (self) { identifier = identifier_; } return self; } 
+6
source share
2 answers

If you use ARC, the difference between them is not that big. If you are not using ARC, the difference is extremely important.

The alloc/init component gives you a reference to ownership. This means you should release later. The classnameWithFoo variant returns a non-ownership link. You cannot release it.

This follows Cocoa's usual naming conventions. All methods return unused (auto-implemented) instances, with the exception of methods starting with alloc , copy , mutableCopy and new . These returns own the links you must release .

Which one to use is basically a matter of taste. However, if you need temporary objects that you can quickly recycle, the alloc option results in slightly fewer method calls ( autorelease ) in a loop, and also reduces the maximum amount of memory. However, in most cases, this reduced cost is negligible.

+5
source

IMO, the biggest difference between the two approaches comes from the fact that with the help of the "class constructor" you get an auto-implemented object; This is the most convenient option when you:

  • assign the selected object to retain properties;

  • when you create "temporary" objects (think of the various NSString methods that build a line from another line: in many cases this happens, you need to "chain" such calls, the constructor allows you to "forget" about memory management);

  • when you add an object to some object that saves it (think: addSubview )

In such cases, the syntactic advantage of the “class constructor” is first and foremost, but I think that also makes your code “more secure” in terms of memory management.

On the other hand, when you create an object to assign property to it (or directly for ivar, for which you do not have a property), then alloc/init will be fine and preferable to the "constructor" (IMO).

So, in the end, it depends on how you are going to use the objects you select. The class constructor is a convenient method.

+5
source

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


All Articles