zoukankan      html  css  js  c++  java
  • 自动释放池

    • 1.autorelease的基本用法
    • 1> 会将对象放到一个自动释放池中
    • 2> 当自动释放池被销毁时,会对池子里面的所有对象做一次release操作
    • 3> 会返回对象本身
    • 4> 调用完autorelease方法后,对象的计数器不变
    • 2.autorelease的好处
    • 1> 不用再关心对象释放的时间
    • 2> 不用再关心什么时候调用release
    • 3.autorelease的使用注意
    • 1> 占用内存较大的对象不要随便使用autorelease
    • 2> 占用内存较小的对象使用autorelease,没有太大影响
     
    •自动释放池的应用
    • 1> 在iOS程序运行过程中,会创建无数个池子。这些池子都是以栈结构存在(先进后出)
    • 2> 当一个对象调用autorelease方法时,会将这个对象放到栈顶的释放池
    • 自动释放池的创建方式
    • 1> iOS 5.0前
    • NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    • [pool release]; // [pool drain];
    • 2> iOS 5.0 开始
    • @autoreleasepool {
    •   
    • }
     
    •1  系统自带的方法里面没有包含alloc、new、copy,说明返回的对象都是autorelease的
    • 2  开发中经常会提供一些类方法,快速创建一个已经autorelease过的对象
    • 1> 创建对象时不要直接用类名,一般用self
    • + (id)person
    • {
    •    return [[[self alloc] init] autorelease];
    • }
     
    自动释放池的嵌套
    •autorelease 会将对象添加到它最近的自动释放池

       @autorelease {

                 Person *person = [[Person alloc] init];

                 [person autorelease];

                 @autorelease{

                           Dog *dog = [[ Dog alloc] init];

                           [dog autorelease];

                  }

       }

     
    自动释放池案例
     
    •  for(int i=0; i<1000000; i++){
    •        NSMutableArray *array = [[NSMutableArray alloc] init];
    •        [array  autorelease];
    •  }
    •问题?
     
    •正确的写法:   累计不超过1000个对象就会释放一次
    •    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    •    for(int i=0; i<100000; i++){
    •         if (i%1000 == 0){
    •               [ pool release];
    •               pool = [[NSAutoreleasePool alloc] init];
    •         }
    •         NSMutableArray *array = [[ NSMutableArray alloc] init];
    •         [array autorelease];
    •    }
     
  • 相关阅读:
    js调用oc方法 UIWebView 跳 到另一个UIWebView
    可变cell,自适应cell,理解iOS 8中的Self Sizing Cells和Dynamic Type
    设置textField的placeholder字体的颜色,默认是灰色
    设置按钮(UIButton)为圆角矩形
    UITextView限制输入字数
    如何更好地限制一个UITextField的输入长度
    uitableview style类型为Grouped时,去掉上面空白的方法
    python note 01 计算机基础与变量
    Leetcode61.旋转链表
    Leetcode 430. 扁平化多级双向链表
  • 原文地址:https://www.cnblogs.com/chenzq12/p/6214613.html
Copyright © 2011-2022 走看看