1
votes

I've been coding in Objective-C for a few months now and I've noticed that sometimes a class is instantiated (as recommended by documentation) with an init method. Therefore, one must alloc first, and then init. [[Example Class Alloc] initWithProperty1:andTwo:]. However, sometimes the doc recommends using "factory methods" as constructors. Such as [NSArray arrayWithObjects:__].

It seems that with a factory/class method you get the allocation done behind the scenes and the actual method is indistinguishable from the init, AFAIK.

Therefore, what is the practical reason to prefer one over the other? Is my analysis of the two being nearly identical even correct?

1

1 Answers

2
votes

I recommend using factory method if there is one that does what you need. Aside from the syntactic sugar (shorter), there are also differences in the object's ownership (and hence who should free it). You shouldn't worry so much about memory if you use ARC.

From Apple's documentation:

Factory methods can be more than a simple convenience. They can not only combine allocation and initialization, but the allocation can inform the initialization. As an example, let’s say you must initialize a collection object from a property-list file that encodes any number of elements for the collection (NSString objects, NSData objects, NSNumber objects, and so on). Before the factory method can know how much memory to allocate for the collection, it must read the file and parse the property list to determine how many elements there are and what object type these elements are.

That is a little mystic but consider a use case like this: you want to populate an NSMutableArray with the content of a file. If you choose "alloc and init", the OS must constantly allocate new memory to store the additional data as you read them from the file. The class method needs to parse the file first, so it know how many lines there are and how big of a memory it should ask for in one go.