我无法理解如何@autoreleasepool工作。 请看下面的例子中,我创建了一个audiofile的一个AVAssetReader。 为了使内存的影响问题,我重复这个步骤1000次。
#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
void memoryTest() {
NSURL *url = [[NSURL alloc] initWithString:@"path-to-mp3-file"];
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:url options:nil];
AVAssetReader *reader = [[AVAssetReader alloc] initWithAsset:asset error:NULL];
}
int main(int argc, const char * argv[]) {
// Breakpoint here (A)
@autoreleasepool {
for(int i = 0; i < 1000; i++) {
memoryTest();
}
}
// Breakpoint here (B)
return 0;
}
前和断点和断点BI在循环之后拍了一下我在Xcode调试导航应用程序的内存使用情况。 在A点我的应用程序消耗约内存1.5MB。 在B点是约80MB。 有趣的是在B点的内存使用量降至约4MB当我把autoreleasepool像这样的循环中:
for(int i = 0; i < 1000; i++) {
@autoreleasepool { memoryTest(); }
}
为什么位置很重要? (断点-在两种情况下-是autoreleasepool以外!)在任一情况下,在点B处的存储器消耗正比于循环的次数。 我失去了别的东西在这里释放它的内存?
我认为在导航器中存储的图表被推迟的,只是断点之前添加usleep不会改变任何东西。 如果我改变memoryTest()来
void memoryTest() {
NSURL *url = [NSURL URLWithString:@"path-to-mp3-file"];
}
@autoreleasepool的位置并不重要。 是不是很奇怪吗?
我使用的Xcode 6,OS X SDK 10.10与ARC启用。