Stefan Fachmann
Stefan Fachmann

Reputation: 545

Objective-C .mm in initializer and class factory method

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?

Upvotes: 0

Views: 246

Answers (3)

Jay O'Conor
Jay O'Conor

Reputation: 2495

In the second example, you didn't create the string. You only create objects by invoking methods that begin with alloc, new, copy, or mutableCopy.

You may take ownership, if you like, by invoking retain, but then you're also responsible for invoking release. In this example, there's no need. You don't need the string any more. What the caller does with it is their responsibility.

When invoking a factory method like this, you typically receive an autoreleased object. But you don't really need to think about that. Because you didn't create it (because you didn't use a method beginning with alloc, new, copy, or mutableCopy to get that string), all you need to do is think about the retain count delta -- do you need to retain it to keep it from disappearing from underneath you. Since it's just being returned to the caller, the answer in this example is no.

Upvotes: 1

iHunter
iHunter

Reputation: 6215

You are right, the factory method internally calls the alloc, and thus returns retained object, but it adds that object to the nearest autorelease pool, so when that pool will be drained, the object will be released.

Upvotes: 0

ericg
ericg

Reputation: 8742

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.

Upvotes: 2

Related Questions