我在阅读苹果公司的关于内存管理的文档时,看到了自动释放池块,这让我开始思考。
Any object sent an autorelease message inside the autorelease pool block is
released at the end of the block.
我不确定我完全理解这个问题。在自动释放池块内创建的任何对象都会在块结束时被释放,因为这是它的生命周期。当对象到达块的结尾时,它将自动释放,那么为什么还需要调用autorelease方法呢?
为了更清楚地说明,我将给出一个例子:
@autoreleasepool {
MyObject *obj = [[MyObject alloc] init]; // no autorelease call here
/* use the object*/
//....
// in the end it should get deallocated because it's lifespan ends, right?
// so why do we need to call autorelease then?!
}
注意:请不要告诉我因为ARC的存在我们不需要做一些事情,因为ARC会自动处理它们。我完全意识到这一点,但我想在短暂的时刻内先放置ARC,以便理解内存管理机制。
autorelease
只是将对象添加到自动释放池中。"当自动释放池结束时,所有计数为0的自动释放对象将释放它们的内存。"不,当自动释放池结束时,它会释放池中的所有对象。release
可以在任何地方(无论是由自动释放池还是其他地方)调用,如果release
之前的保留计数为1,则可能导致对象被释放。 - newacct