Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a local autorelease pool to save up memory?

Apple says that this is a good idea for saving memory. What would that look like in code?

like image 743
Thanks Avatar asked Apr 12 '09 18:04

Thanks


People also ask

What is an Autorelease pool?

An autorelease pool stores objects that are sent a release message when the pool itself is drained. Important. If you use Automatic Reference CountingReference CountingIn computer science, reference counting is a programming technique of storing the number of references, pointers, or handles to a resource, such as an object, a block of memory, disk space, and others. In garbage collection algorithms, reference counts may be used to deallocate objects that are no longer needed.https://en.wikipedia.org › wiki › Reference_countingReference counting - Wikipedia (ARC), you cannot use autorelease pools directly. Instead, you use @autoreleasepool blocks.

What is pool in Objective C?

A pool is created at the first brace and is automatically drained at the end of the scope. Any object autoreleased within the scope is sent the release message at the end of the scope. Let's take a look at this example: for (int i = 0; i < 100000; i++) {

What is Autoreleasepool Swift?

Memory management in swift is handled with ARC (= automatic reference countingreference countingIn computer science, reference counting is a programming technique of storing the number of references, pointers, or handles to a resource, such as an object, a block of memory, disk space, and others. In garbage collection algorithms, reference counts may be used to deallocate objects that are no longer needed.https://en.wikipedia.org › wiki › Reference_countingReference counting - Wikipedia). This means that active references to objects are counted and objects are released when they aren't referenced anymore.


1 Answers

Usualy you don't need to create autorelease pool, because system cares about this. But, sometimes you need to do this. It's usualy in big loops. Code would look like this:

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
int i;    
for (i = 0; i < 1000000; i++) {    
  id object = [someArray objectAtIndex:i];
  // do something with object
  if (i % 1000 == 0) {
    [pool release];
    pool = [[NSAutoreleasePool alloc] init];
  }
}
[pool release];

Autorelease pools are kept as a stack: if you make a new autorelease pool, it gets added to the top of the stack, and every autorelease message puts the receiver into the topmost pool.

like image 167
iPera Avatar answered Nov 14 '22 21:11

iPera