Apple says that this is a good idea for saving memory. What would that look like in code?
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.
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++) {
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With