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 autorelease];
}
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
newis expected to return a retained object and most other class methods are expected to return an autoreleased object. Since your method does not start withnewbut 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:There’s a few other conventions that you’re not following (and you probably should).
initis an initializer. It should be an instance method and it should return eitherselfor the results of another initializer. Read Apple’s documentation on how to properly create an init method.MyDetails.