Memory leak versus best object release practice
Leak:
+ ( myDetails* ) initEmptySlideDetails { //ok
myDetails* theObject = [[myDetails alloc] init];
theObject.ID = 0;
return theObject;
}
Question 1: Is this the right way to return an object that I also want to release to avoid memory leak?
No leak:
+ ( myDetails* ) initEmptySlideDetails { //ok
myDetails* theObject = [[myDetails alloc] init];
theObject.ID = 0;
return [theObject auto开发者_如何学Crelease];
}
Question2: When I use the object, do I need to force a retain? (because of the autorelease).
myDetails* myDetails = [myDetails initEmptySlideDetails];
Hope i'm clear... :)
The reason that you're getting warned for a leak in the first example is because of a naming convention. Generally, a class method that starts with new
is expected to return a retained object and most other class methods are expected to return an autoreleased object. Since your method does not start with new
but you are returning a retained object, the analyzer thinks that you are going to leak an object. The solution here is to give your method a better name, something like:
+ (MyDetails *) newMyDetails;
There's a few other conventions that you're not following (and you probably should).
- Any method that begins with
init
is an initializer. It should be an instance method and it should return eitherself
or the results of another initializer. Read Apple's documentation on how to properly create an init method. - Class names always start with capitalized letters. Your class should be named
MyDetails
.
Q1: "initEmptySlideDetails" is a poor name for a function, as it is likely to be mistaken for an initializer for your class. If you name the method to start with 'alloc' or 'new', or name it to contain the word 'copy', then you should not autorelease it. Otherwise you should. At least if you want to follow Apple's standard memory management rules.
Q2: An object that is autoreleased may be used within the current method, passed to other methods, and may be returned from your current method. But it cannot be saved for later without a retain. Note the retain may be implicit, e.g. if you assign it to a property declared "retain" or add it to an NSArray, NSDictionary, NSSet, or other collection that retains its members. Also, if you mess with NSAutoreleasePool that may cause objects to be released earlier.
If you are showing leaks with the above code, something is wrong. The first set of code is correct.
How do you know there is a leak? instruments? static analysis?
It may be that you are confusing the static analyzer with your choice of the prefix init.
try setupEmptySlideDetails or makeEmptySlideDetails instead.
Edit
now the second set of code is correct.
Q2
you don't need a retain there. Autorelease means that object will be released at some future date after your method ends. (it might be soon or may be several seconds later). In the meantime, while you are using myDetails, it's gonna be okay.
精彩评论