Autorelease use of automatic release pool
- With ARC development, the compiler automatically adds retain, release, and Autorelease based on the code structure at compile time.
- MRC Memory management principles: who applies, who releases encounters Alloc/copy/retain all need to add release or Autorelease
- Autorelease is just a token that will delay release when a Autorelease object goes out of its scope, it is added to the nearest Autorelease pool, and when the pool starts pouring, The release method is sent to all objects inside the pool, releasing all objects in the pools.
The release of the Autorelease pool for the auto-free pools is related to the message loop
- Simulate a simple message loop
void Click (int type) {printf ( "you performed operation%d \ n", type);} int Main (int argc, const char * argv[]) { @autoreleasepool {while (yes) {printf ( "Please enter the action to be performed, 0 end:"); int N; scanf ( "%d", &n); //receives the input of the user waiting for the blocker to run if (n = = 0) { printf ( "program end \ n"); break;} else{click (n); continue;} }} return 0;}
- The execution of a message loop
Event occurrence (for example, click), convert to an event object, turn on Autorelease pool-> execute our processing code, the temporary variables generated in the code can be placed in the pool->pool destroy- Next loop
- Message loops for the main thread
There is an open message loop by default in the main thread, creating an auto-release pool when the event is turned on, dumping the release pool at the end of the event
Automatic release of pool usage scenarios
- Create a large number of temporary variables in a loop
- In a child thread
- The following is used for the auto-free pool in the loop:
for (int i = 0; i < largeNumber; ++i) {@autoreleasepool{ NSString *str = @"Hello World"; str = [str stringByAppendingFormat:@" - %d", i]; str = [str uppercaseString]; NSLog(@"%@", str);}}
Create a lot of temporary objects in the loop nsstring, in the case of the method is not finished, each created object is not released, so we use the automatic release pool, at the beginning of each cycle to put the temporary variable nsstring into the pool, and so each time the end of the cycle to dump the pool, The release nsstring temporary variable is thus released each time.
Autorelease use of automatic release pool