@autoreleasepool内存管理

来源:互联网 发布:原型图软件 编辑:程序博客网 时间:2024/05/21 11:22

虽然OC提供了@autoreleasepool这样方便快捷管理内存的方案,但它并不像Java一样能够全自动化,很多时候还是需要我们自己手动释放内存。自动释放池是OC里面的一种内存回收机制,一般可以将一些临时变量添加到自动释放池中,统一回收释放,当自动释放池销毁时,池里面的所有对象都会调用一次release,也就是计数器会减1,但是自动释放池被销毁了,里面的对象并不一定会被销毁。

 

#import <Foundation/Foundation.h>

@interface Student :NSObject

@property (nonatomic,assign)int age;

+(id)student;

+(id)studentWithAge:(int)age;

@end



#import "Student.h"

@implementation Student

+(id)student{

    return [[[Studentalloc]init]autorelease];

}

+(id)studentWithAge:(int)age{

    //Student *stu=[Student student];

    Student *stu=[self student];  //self指向当前类

    stu.age=age;

    return stu;

}

@end


#import <Foundation/Foundation.h>

#import "Student.h"

int main(int argc,constchar * argv[])

{


    //创建自动释放池

    @autoreleasepool {

             Student *stu=[Studentstudent];

        

    }

    return 0;

}




OC对象发送一条autorelease消息,就会把这个对象添加到最近的自动释放池中也就是栈顶释放池中,Autorelease实际上是把对release的调用延迟了,对于每一次autorelease,系统只是把对象放入了当前的autorelease pool中,当pool被释放时,pool中所有的对象都会被调用release。

 

 


注意:

1.在ARC下,不能使用[[NSAutoreleasePoolalloc]init](在5.0以前可以使用),而应该使用@autoreleasepool

2.不要把大量循环放在autoreleasepool中,这样会造成内存峰值上升,因为里面创建的对象要等释放池销毁了才能释放,这种情况应该手动管理内存。

3.尽量避免大内存使用该方法,对于这种延迟释放机制,尽量少用

4.SDK中利用静态方法创建并返回的对象都已经autorelease,不需要我们自己手动release。


1 0
原创粉丝点击