oc53--autorelease注意事项

//
//  main.m
//  autorelease注意事项

#import <Foundation/Foundation.h>
#import "Person.h"

int main(int argc, const char * argv[]) {

    
    Person *p1 = [[Person alloc] init];
    @autoreleasepool {
        Person *p2 = [[[Person alloc] init] autorelease];
        [p2 run];
        
        // 2.在自动释放池中创建了对象, 一定要调用autorelease,才会将对象放入自动释放池中
        Person *p3 = [[Person alloc] init];
        [p3 run];
        
        // 3.只要在自动释放池中调用autorelease, 就会将对象放入自动释放池,即使p1在外面定义的。
        p1 = [p1 autorelease];
        [p1 run];
    }
    // 1.一定要在自动释放池中调用autorelease, 才会将对象放入自动释放池中
    Person *p4 = [[[Person alloc] init] autorelease];
    
    
    
    
    // 4.一个程序中可以创建N个自动释放池, 并且自动释放池还可以嵌套
    // 如果存在多个自动释放池的时候, 自动释放池是以 "栈" 的形式存储的
    // 栈的特点: 先进后出
    
    // 给一个对象方法发送一条autorelease消息, 永远会将对象放到栈顶的自动释放池
    @autoreleasepool { // 创建第一个释放池
        @autoreleasepool { // 创建第二个释放池
            @autoreleasepool { // 创建第三个释放池
                Person *p = [[[Person alloc] init] autorelease];//放在第三个自动释放池里面,因为第三个释放池在最上面。
                [p run];
            } // 第三个释放池销毁,会将p释放。
            
            Person *p1 = [[[Person alloc] init] autorelease];//放在第二个释放池里面,因为第二个池子在最上面,
            
        }// 第二个释放池销毁,此时p1会销毁
    }// 第一个释放池销毁
    
    
    
    
    
    @autoreleasepool {
        // 千万不要写多次autorelease,一个alloc, new对应一个autorelease
        Person *p1 = [[[[Person alloc] init] autorelease] autorelease];//当池子销毁的时候会发送2次release消息,过度释放。
        
        // 如果写了autorelease就不要写release
        // 总之记住: 一个alloc/new对应一个autorelease或者release
        Person *p = [[[Person alloc] init] autorelease];
        [p release];
    }
    
    return 0;
}
//
//  ViewController.m
//  自动释放池大对象问题
//
//  Created by xiaomage on 15/6/26.
//  Copyright (c) 2015年 xiaomage. All rights reserved.
//

#import "ViewController.h"
#import "Person.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    /*
    // 1.不要再自动释放池中使用比较消耗内存的对象, 占用内存比较大的对象
    @autoreleasepool {
        Person *p = [[[Person alloc] init] autorelease];
        
        // 假如p对象只在100行的地方使用, 以后都不用了
        
        // 一万行代码,p对象需要在一万行时候释放,p一直占用着内存。
    }
     */
    
   
    // 2.尽量不要再自动释放池中使用循环, 特别是循环的次数非常多, 并且还非常占用内存
    @autoreleasepool {
        for (int i = 0; i < 99999; ++i) {
            // 每调用一次都会创建一个新的对象
            // 每个对象都会占用一块存储空间
            Person *p = [[[Person alloc] init] autorelease];
        }
    } // 只有执行到这一行, 所有的对象才会被释放
   
    
    /*
    for (int i = 0; i < 99999; ++i) {
        @autoreleasepool {
             Person *p = [[[Person alloc] init] autorelease];
        } // 执行到这一行, 自动释放池就释放了
    }
     */
    NSLog(@"--------");
}

@end
原文地址:https://www.cnblogs.com/yaowen/p/7428901.html