美文网首页
iOS Autorelease

iOS Autorelease

作者: CrystalZhu | 来源:发表于2020-02-23 16:30 被阅读0次

    顾名思义,autorelease就是自动释放,这看上去很ARC,但实际上它更类似于C语言中自动变量(局部变量)的特性.
    C语言的自动变量,程序执行时,某自动变量超过其作用域该自动变量将自动被废弃.
    区别在于autorelease可以被编程人员设定变量的作用域
    具体的使用方法如下:
    ①生成并持有NSAutoreleasePool对象
    ②调自己分配对象的autorelease实例方法
    ③ 废弃NSAutoreleasePool对象
    用代码表示:

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    id obj = [[NSObject alloc] init];
    [obj autorelease];
    [pool drain];  //等同于 [pool release];
    

    当大量产生autorelease的对象时,只要不放弃NSAutoreleasePool对象,那么生成的对象就不能释放,因此有时会产生内存不足现象.eg: 读入大量图像的同时改变其尺寸,图像文件读入到NSData对象,并从中生成新的UIImage对象.这种情况下,就会大量产生autorelease的对象.

    for (int i=0, i < 图像数; ++i){
      //读入图像,大量产生auto release的对象,由于没有废弃NSAutoreleasePool对象,最终导致内存不足
    }
    

    所以需要在适当的地方生产,持有或废弃NSAutoreleasePool对象

    for (int i = 0; i<图像数; ++i){
      NSAutoreleasePool *pool = [[NSAutorelease alloc] init];
      /*
        读入图像,大量产生autorelease的对象
      */
        [pool drain];
      /*
        通过[pool drain] autorelease的对象被一起release
      */
    }
    

    另外,Cocoa框架中也有很多类方法,用于返回autorelease的对象,比如:NSMutableArray类的arrayWithCapacity类方法.

    id array = [NSMutableArray arrayWithCapacity: 1];
    

    此源代码等同于以下源代码:

    id array = [[[NSMutableArray alloc] initWithCapacity:1] autorelease];
    

    说明:
    NSInteger = 5时,初始化方法capacity后的NSInteger代表了开辟内存的一个单位初始化在内存中开辟了5个内存,如果之后数组元素多于5个,则会开辟新的52个新的内存
    因为数组的连续内存的特征,单位是5,把之前的5个元素的内容拷贝到新的10个内存里面,把第六个也放进去,然后释放初始状态创建的内存,最后得到一块够用的连续的内存5
    2.

    在Coco框架中,相当于程序主程序的NSRunloop或者其他程序可运行的地方,对NSAutoreleasePool对象进行生产持有和废弃处理.

    NSAutoreleasePool在新版的Xcode中使用会报错,因为新版的Xcode引入了ARC特性来自动管理内存.

    所以现在使用

    @autoreleasePool{
      // omitted      使用@autoreleasepool
    }
    

    相关文章

      网友评论

          本文标题:iOS Autorelease

          本文链接:https://www.haomeiwen.com/subject/mxaafhtx.html