background image

动帮你写好。

autorelease pool 的真名是 NSAutoreleasePool。

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
6.2
NSAutoreleasePool 内部包含一个数组(NSMutableArray),用来保存声明为 autorelease 的
所有对象。如果一个对象声明为

autorelease,系统所做的工作就是把这个对象加入到这个数

组中去。
ClassA *obj1 = [[[ClassA alloc] init] autorelease]; //retain count = 1,把此对象加入 autorelease 
pool 中
6.3
NSAutoreleasePool 自身在销毁的时候,会遍历一遍这个数组,release 数组中的每个成员。
如果此时数组中成员的

retain count 为 1,那么 release 之后,retain count 为 0,对象正式被

销毁。如果此时数组中成员的

retain count 大于 1,那么 release 之后,retain count 大于 0,此

对象依然没有被销毁,内存泄露。
6.4
默认只有一个

autorelease pool,通常类似于下面这个例子。

int main (int argc, const char *argv[])
{
NSAutoreleasePool *pool;
pool = [[NSAutoreleasePool alloc] init];

// do something

[pool release];
return (0);
} // main

所有标记为

autorelease 的对象都只有在这个 pool 销毁时才被销毁。如果你有大量的对象标

记为

autorelease,这显然不能很好的利用内存,在 iphone 这种内存受限的程序中是很容易

造成内存不足的。例如:
int main (int argc, const char *argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
int i, j;
for (i = 0; i < 100; i++ )
{
for (j = 0; j < 100000; j++ )
    [NSString stringWithFormat:@"1234567890"];//产生的对象是 autorelease 的。
}
[pool release];
return (0);
} // main
(可以参考附件中的示例程序

memman-many-objs-one-pool.m,运行时通过监控工具可以发

现使用的内存在急剧增加,直到

pool 销毁时才被释放)你需要考虑下一条。