Apart from the standard [[MyClass alloc] init] pattern, some objects are built from static methods like MyClass *obj = [MyClass classWithString:@"blabla"]
According to widespread memory management guides (including Apple’s), you’re only responsible for releasing the objects that you alloc.
Can anyone provide me with a template for such methods? How do you return the allocated object ([self alloc]; return self;, perhaps)? How do you make sure that it will be released?
They are class methods, not static methods1. This specific type, creating autoreleased objects, can be referred to as “factory methods” (formerly also “convenience constructors”), and they are discussed in the Concepts in ObjC Guide. They go something like this:
Where
Whatsisis your class, andThingummyis another class which your class uses.If you’re not compiling with ARC, the convention is to
autoreleasethe instance before returning it.The
instancetypekeyword was introduced by Clang for these kinds of methods; combined withself(which is the class object itself2 in a class method) it allows correct subclass behavior: the method produces an instance of the class which received the message.3instancetypeallows the compiler to do more strict typechecking thanid.An illustration of this usage in subclasses from the framework:
+[NSString stringWithFormat:]returns anNSStringinstance, whereas+[NSMutableString stringWithFormat:], returns an instance of the subclassNSMutableString, withoutNSMutableStringbeing required to explicitly override the method.As discussed by the [Fundamentals][1] doc, there are other uses for these factory methods, such as accessing a singleton, or appraisal of the necessary memory allocation before it’s performed (possible, but less convenient, with a standard
alloc/initpair).1“Static methods” in Java or C++, “class methods” in Objective-C. There’s no such thing as static methods in ObjC
2Whereas in an instance method
selfis, sensibly, a reference to the instance.3Previously, like the usual initialization methods (
initWith...), you would have usedidas the return type. Using a specific class name unnecessarily forces subclasses to override the method.