Autorelease & AutoreleasePool

   __weak NSString * weak_String; 
   __weak NSString * weak_StringAutorelease;

 void createString() {
    NSString *string = [[NSString alloc] initWithFormat:@"xxxx-string"];    // 创建常规对象
    NSString * stringAutorelease = [NSString stringWithFormat:@"xxxx-autorealse-string"];
    weak_String = string;
    weak_StringAutorelease = stringAutorelease;
    NSLog(@"---------in the createString-------");
    NSLog(@"--%@-",weak_String);
    NSLog(@"--%@",weak_StringAutorelease);
}
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        createString();
        NSLog(@"---------in the autoreleasepool-------");
        NSLog(@"--%@-",weak_String);
        NSLog(@"--%@",weak_StringAutorelease);
      
    }
     NSLog(@"---------in the main-------");
    NSLog(@"--%@-",weak_String);
    NSLog(@"--%@",weak_StringAutorelease);  
    return 0;
}

通过clang -rewrite-objc 把oc代码转为c/c++代码,可以分析出
objc_autoreleasePoolPush(void)------>[object autorelease]----->objc_autoreleasePoolPop(void)

Autorelease对象什么时候释放?

在没有手加@autoreleasepool的情况下,autorelease 对象是在当前的runloop迭代结束时释放的,而它能够释放的原因是系统在每个RunLoop迭代中都加入了自动释放池Push和pop

Autorelease & AutoreleasePool_第1张图片
屏幕快照 2017-09-12 上午9.26.33.png

autorelease提供这样的功能,不立即释放,注册到autoreleasepool中,pool结束时,自动调用release

three occasions when you might use your own autorelease pool blocks:
1.If you are writing a program that is not based on a UI framework, such as a command-line tool.

  1. If you write a loop that creates many temporary objects.
  2. If you spawn a secondary thread.

autorelease 实现

class AutoreleasePoolPage {
    static size_t const COUNT = SIZE / sizeof(id);

    magic_t const magic;
    id *next;
    pthread_t const thread;
    AutoreleasePoolPage * const parent;
    AutoreleasePoolPage *child;
    uint32_t const depth;
    uint32_t hiwat;
    static inline void *push() {
      //相当于生成或持有NSAutoreleasePool类对象
    }
    static inline void pop(void *token) {
     //废弃NSAutoreleasePool 类对象
    }
   static inline id autorelease(id obj)
    {
     //相当于NSAutoreleasePool类的addObject类方法
        AutoreleasePoolPage *page = //取得正在使用的AutoreleasePoolPage实例

    }

}

参考链接

黑幕背后的Autorelease
AutoreleasePool的原理和实现
Using Autorelease Pool Blocks

你可能感兴趣的:(Autorelease & AutoreleasePool)