标签:
自动释放池是OC里面的一种内存回收机制,一般可以将一些临时变量添加到自动释放池中,统一回收释放,当自动释放池销毁时,池里面的所有对象都会调用一次release,也就是计数器会减1,但是自动释放池被销毁了,里面的对象并不一定会被销毁。
OC对象发送一条autorelease消息,就会把这个对象添加到最近的自动释放池中也就是栈顶释放池中, Autorelease实际上是把对release的调用延迟了,对于每一次autorelease,系统只是把对象放入了当前的autorelease poo(栈顶释放池中)l中,当pool被释放时,pool中所有的对象都会被调用release。
1.在ARC下,不能使用 [[ NSAutoreleasePool alloc ] init ](在5.0以前可以使用),而应该使用@autoreleasepool
2.不要把大量循环放在autoreleasepool中,这样会造成内存峰值上升,因为里面创建的对象要等释放池销毁了才能释放,这种情况应该手动管理内存。
3.尽量避免大内存使用该方法,对于这种延迟释放机制,尽量少用
4.SDK中利用静态方法创建并返回的对象都已经autorelease,不需要我们自己手动release。
----------------------------------------------------
Autorelease will not change the Object counter,just throw them into a pool.
When destroy the pool?
}
-------------------------------------------
Way of writing
1
main()
{
@autorelease{
Student *stu=[[Student alloc]init];
[stu autorelease];
Student *stu1=[[Student alloc]init];
[Stu1=autorelease];
}
return 0;
}
2 //Most common used
Student *stu=[[[Student alloc]init]autorelease];
Student *stu1=[[[Student alloc]init]autorelease];
-------------------------------------------
//Create Autoreleasepool
1. iOS 5.0 after
@ autoreleasepool{
//code here
}
2.iOS 5.0 before
NSAutoreleasePool *pool=[[NSAutoreleasePool alloc]init];
//code here
[pool release];
// Or [pool drain]; Only have difference in Mac development between release and //drain.
-------------------------------------------------
//Another clever use of autorelease
//Create a static method to speedly create an object
//Student.h ( Method name is the same as class name by default)
//+(id)student;
//+(Student)student;
//Student.m
+(id)student{
Student *stu=[[[Student alloc]init]autorelease];
return stu;
}
main(){
autoreleasepool{
Student *stu=[Student student]
}
}
//latent rules
//iOS Static method/Object actually don‘t need developers to manage memory
//They do autorelease inside themselves
-----------------------------------
标签:
原文地址:http://www.cnblogs.com/yesihoang/p/4487503.html