Iphone memory management

I have a method that returns NSMutableArray:

// class implementation Students

-(NSMutableArray *)listOfStudents {
  NSMutableArray *students = [[NSMutableArray alloc] init];
  //add objects to students and other operations here
  return students;
}

      

The problem here is when and where do I release the students of the facility? If it was an instance variable, I would add [student graduation] to the dealloc method, but it isn't. Class Students have allocated an object, so it owns the new NSMutableArray, and it should release it, right? Since I can't let it go before returning, the only option I see here is to return it as:

return [students autorelease];

      

But don't use auto-update items on iPhone. This method will be called many times ... and I would like to free the memory as soon as possible. Also, the autoresource pool is in the main function and it looks like it will take a while to clear up the mess.

How do you do it?

+1


a source to share


2 answers


I try to avoid using auto ads wherever I am in my iPhone apps, but there are times when it doesn't hurt you. If the array that you generate with this method is saved for a long enough duration, then you will not sacrifice any performance or memory usage by returning it as an auto-implemented result.

However, if you will be using and discarding the returned object quite often, you can do something different. I have a naming convention with my methods that if something is prefixed with "generate", like generateStudentsArray, it returns an object owned by the caller and must be manually released (like with a copy). This avoids the use of auto-implemented objects, but adds one more thing to keep in mind when managing memory.



Also, since allocating / freeing memory is expensive (especially on the iPhone), you might want to avoid frequent allocations and deallocations within a method that is called quite a bit, and instead recycle a volatile array by creating it ahead of time and passing it to the method. which only adds the contents of the array.

+1


a source


You are correct autorelease

- this is a standard idiom to use in such a situation.

UIKit actually creates an autorun pool at the beginning of each event loop and releases it at the end, so your autorun objects will be cleaned up; they won't hang out forever.



If you had a loop that called this method many times during the same event loop, you might want to create your own autorun pool inside this loop so that these objects are freed at the end of each iteration, rather than creating a load of objects that will issued at the end of the current event cycle.

But unless you are doing something like this, or you are facing another specific out of memory situation, the standard UIKit autonomy pools should handle this fine.

0


a source







All Articles