table of Contents
text
1: NSAutorelease implementation principle
1: Starting from the main function
int main(int argc, const char * argv[]) { @autoreleasepool { // insert code here... NSLog(@"Hello, World!"); } return 0; }
2: @autoreleasepool
2.1:@autoreleasepool
what exactly is it? We use the command line for the compiler to rewrite the file: clang -rewrite-objc main.m
$ clang -rewrite-objc main.m
int main(int argc, const char * argv[]) { /* @autoreleasepool */ { __AtAutoreleasePool __autoreleasepool; NSLog((NSString *)&__NSConstantStringImpl__var_folders_49_sdbnp0nd07q4m_sh4_gw52r40000gn_T_main_9e48ee_mi_0); } return 0; }
In this file, there is a very strange structure body , wrote the previous comment . That it is converted to: __ structure of AtAutoreleasePool. __AtAutoreleasePool
/* @autoreleasepopl */
@autoreleasepool {}
2.2: can be found by comparing apples around @autoreleasepool is replaced by a structure type __AtAutoreleasePool declare a local variable of type __AtAutoreleasePool
struct __AtAutoreleasePool { __AtAutoreleasePool () {atautoreleasepoolobj = objc_autoreleasePoolPush ();} ~ __AtAutoreleasePool () {objc_autoreleasePoolPop (atautoreleasepoolobj);} Void * atautoreleasepoolobj; };
can be seen:
__AtAutoreleasePool () constructor calls objc_autoreleasePoolPush (),
~ __AtAutoreleasePool () calls the destructor objc_autoreleasePoolPop ()
2.3: This shows that our main
function is actually this:
int main(int argc, const char * argv[]) { { void * atautoreleasepoolobj = objc_autoreleasePoolPush(); // do whatever you want objc_autoreleasePoolPop(atautoreleasepoolobj); } return 0; }
@autoreleasepool
Help us less just two lines of code to write, to make the code look more beautiful, then you want to analyze the automatic release of the pool according to the above two methods
to sum up