我正在阅读苹果关于内存管理的文档,当我得到自动释放池块,有些东西让我想到.
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?! }
PS:请不要告诉我,因为ARC,我们不需要做一些事情,因为ARC照顾他们.我完全意识到这一点,但是我想让ARC留下一会儿来了解内存管理的机制.
解决方法
自动释放只是从对象中删除保留计数,它不像c中那样“释放”内存.当自动释放池结束所有自动释放的对象的计数为0将会释放它们的内存.
有时你会创建很多对象.一个例子将是一个循环,它每次迭代并将新数据添加到字符串时创建新的字符串.您可能不需要以前版本的字符串,并希望释放那些使用的内存.您可以通过明确使用自动释放池来实现此目的,而不是等待它自然完成.
//Note: answers are psudocode //Non Arc Env @autoreleasepool { MyObject *obj = [[MyObject alloc] init]; // no autorelease call here //Since MyObject is never released its a leak even when the pool exits } //Non Arc Env @autoreleasepool { MyObject *obj = [[[MyObject alloc] init] autorelease]; //Memory is freed once the block ends } // Arc Env @autoreleasepool { MyObject *obj = [[MyObject alloc] init]; //No need to do anything once the obj variable is out of scope there are no strong pointers so the memory will free } // Arc Env MyObject *obj //strong pointer from elsewhere in scope @autoreleasepool { obj = [[MyObject alloc] init]; //Not freed still has a strong pointer }