I’m picking up ObjC and Cocoa, which is also my first serious foray into programming in general.
I’m having trouble with the differences between initWith methods, which are called on instances, and factory methods, which are called on classes.
Firstly, why are they called “factory” methods, and is there a proper term for what I’ve dubbed “InitWith” methods?
Secondly, what’s the functional difference? Is it just the memory management implications (that factory methods return an autoreleased object)?
For example, what’s the real difference between [NSString stringWithString: (NSString*)aString] and [[NSString alloc] initWithString: (NSString*)aString]?
The difference between the methods is described in Cocoa’s object ownership policy. You own the object returned from -initWithString: and so must release it, but you don’t own the object returned from +stringWithString and so do not need to release it (furthermore, if you do want to gain ownership of it, you must retain it).
Factory methods are called that because they return an already-created object for you, usually with parameters you provide that are used to configure the object, for the convenience of the programmer.