This is a question related to Objective-C memory management.
On the About Memory Management page there are some examples
- (NSString *)fullName {
NSString *string = [[[NSString alloc] initWithFormat:@"%@ %@",
self.firstName, self.lastName] autorelease];
return string;
}
and the second one
- (NSString *)fullName {
NSString *string = [NSString stringWithFormat:@"%@ %@",
self.firstName, self.lastName];
return string;
}
The only difference is that in the first example an initializer is called, and in the second a class factory method.
Basic memory management rules section is said that after an alloc call I will own the object I allocated. So in the first example I allocate an object and at the same time initialize it. In this I own the object and have to release it. In the second example I don’t. But doesn’t the factory method stringWithFormat: do the same thing in one call, I mean allocating the object and initializing it?
So the main question is, why don’t I have to release the object in the second example?
are there any special memory management rules when implementing a class factory method?
By convention, a class factory method will return an object that is in the autorelease pool. It has done the alloc, init, autorelease for you, just like in the first example. Unless you retain it, when the pool is drained, it will be released.