Jul 11

I have been trying to be a good code citizen and make sure all data I create is released and I don’t cause any memory leaks. I found that I was doing a lot of the following:

NSLog([NSString stringWithFormat:@"Class Name: %@", [object class]]);

Therefore, I didn’t have a reference to the object that I created, and couldn’t explicitly release it. This sort of code convention is just from my Java background, and the fact that I’m used to local method variables to be created on the stack. Since, Obj-C likes to create objects on the heap, you can’t rely on anything going out of scope and getting chewed up (doesn’t have Garbage Collection (at least in the iPhone API)).

After debating it a bit, I learned that “stringWithFormat” returns an NSString that is set to autorelease. That’s great, takes care of my problem. When the event handling loop completes all the string will be released, and all is well. But, there is still one thing bothering me. Here is the documentation for “stringWithFormat”:

XcodeScreenSnapz006

Nowhere does it say the returned string is set to be autoreleased.

In, Session 3 of the Stanford Lectures, Evan Doll states that Method names give you the answer:

Method Names & Autorelease
•Methods whose names includes alloc or copy return a retained object that the caller needs to release
•All other methods return autoreleased objects
•This is a convention- follow it in methods you define!

NSMutableString *string = [[NSMutableString alloc] init];  // We are responsible for calling -release or -autorelease
[string autorelease];
NSMutableString *string = [NSMutableString string];
// The method name doesn’t indicate that we need to release it
// So don’t- we’re cool!

So, there’s the answer. Based on the name of the method, I should know if that object is set to be autoreleased or not. But doesn’t this strike anyone as particularly dangerous? As a developer I am at the mercy of a 3rd Party API developer to follow convention properly. In my mind, this should be documented and done so using any auto-documentation facilities that Xcode has (don’t actually know if it has any).

Tagged with:
preload preload preload