Basic concepts of automatic release pool There is an Autorelease Pool concept in cocoa. As the name suggests, it can store some entities. Set. Objects in the Auto Release pool can be automatically released. The NSObject class provides an autorelease Message. When we send an autorelease message to an object, this object is placed in the Auto Release pool. Create Auto Release pool @ Autoreleasepool { // Write the code after 5.0 for the pooled object} nutoreleasepool * pool = [[nutoreleasepool alloc] init]; // write the code before 5.0 for the pooled object [pool autorelease]; Time when the automatic release pool is destroyed When we send an autorelease message to an object, when the child automatically releases the pool to destroy, every object in the pool will be Send a release message to release them. (1): Let's look at the instance: Create a Person Instance Object and add it to the Auto Release pool to send an autorelease message to the instance object, To view its lifecycle) @autoreleasepool { // Write Person * tom = [[Person alloc] init]; [tom autorelease]; NSLog (@ "pool exist ");} NSLog (@ "pool dead ");
(2): in the preceding example, send a retain message to the object and check the declaration period. @autoreleasepool { // Write "Person * tom = [[Person alloc] init]" after "5.0" into the pool; // 1 [tom autorelease]; [tom retain]; // 2 NSLog (@ "pool exist"); NSLog (@ "tom % ld", [tom retainCount]); [tom release]; // 1 NSLog (@ "tom % ld", [tom retainCount]);
(3): in the preceding example, if there are multiple Auto Release pools, the issue is determined based on the autorelease message sent. The Auto Release pool that the object joins, @autoreleasepool { Person * tom = [[Person alloc] init]; // 1 @ autoreleasepool {// write the code after 5.0 in the pool [tom autorelock]; [tom retain]; NSLog (@ "pool exist"); NSLog (@ "tom1% ld", [tom retainCount]);} NSLog (@ "pool1 dead "); NSLog (@ "tom2% ld", [tom retainCount]);} NSLog (@ "pool2 dead ");
[Summary ]: 1: automatically release the data structure of the pool The Auto Release pool is implemented as a stack. When you create a new auto release pool, it will be added to the top of the stack. Accept autorelease The message object will be placed on the top of the stack. 2: How to hold objects When we use the alloc, copy, and retain objects to obtain an object, we need to be responsible for the destruction of the displayed scheduled object. Will be handed over to the automatic release pool for release (except in singleton Mode) 3: differences between release and drain When we send a release message to the automatically released pool, a release message will be sent to the temporary object in the pool, and it will be destroyed. When a drain message is sent to it, only the former is specified. |