作用
autorelease
的对象,在出了作用域之后,会被自动添加到最近创建的
自动释放池中release
消息,释放池中对象ARC
& MRC
程序中,同样有效自动释放池是什么时候创建的?什么时候销毁的?
创建,运行循环检测到事件并启动后,就会创建自动释放池
for(int i= 0 ;i<100000;i++){
NSArray *array =[[NSArray array] autorelease];
NSLog(@"%@",array);
}
提问:以上代码是否有问题?如果有,如何解决?
解决方法:引入自动释放池
//先定义一个自动释放池
NSAutoreleasePool *pool=nil;
for(int i= 0 ;i<100000;i++){
if (i%100==0) {
//先将原先的100个对象释放掉
[pool release];
//创建一个新的自动释放池
pool = [[NSAutoreleasePool alloc] init];
}
NSArray *array =[[[NSArray alloc] init] autorelease];
NSLog(@"%@",array);
}
[pool release];
如果确实需要使用内存释放池,还是得用,下面列举了哪些场合需要使用
? If you write a loop that creates many temporary objects.You may use an autorelease pool block inside the loop to dispose of those objects before the next iteration. Using an autorelease pool block in the loop helps to reduce the maximum memory footprint of the application.
? If you spawn a secondary thread.You must create your own autorelease pool block as soon as the thread begins executing; otherwise, your application will leak objects. (See Autorelease Pool Blocks and Threads for details.)
原文:http://www.cnblogs.com/donghaoios/p/5089765.html