我开始使用此处描述的技术监控应用程序内存使用情况: Programmatically retrieve memory usage on iPhone
我写了 3 个测试来尝试一下,这就是我发现的:
- (void)test1 {
for (int i = 0; i < 1000; i++) {
NSMutableString *str = [NSMutableString stringWithString:@""];
for (int j = 0; j < 1000; j++) {
[str appendString:@"some really long string some really long string some really long string some really long string some really long string some really long string some really long string some really long string some really long string some really long string some really long string some really long string some really long string some really long string some really long string some really long string "];
}
}
- (void)test2 {
for (int i = 0; i < 100000; i++) {
@autoreleasepool {
NSString *stri = @"";
stri = [NSString stringWithFormat:@"%d some really long string some really long string some really long string some really long string some really long string some really long string some really long string some really long string some really long string some really long string some really long string some really long string some really long string some really long string some really long string some really long string some really long string some really long string some really long string some really", i];
}
}
- (void)test3 {
NSString *str = @"";
for (int i = 0; i < 500; i++) {
str = [str stringByAppendingFormat:@"%d some really long string some really long string some really long string some really long string some really long string some really long string some really long string some really long string some really long string some really long string some really long string some really long string some really long string some really long string some really long string some really long string some really long string some really long string some really long string some really", i];
}
当我调用 test1 或 test3 时,内存被正确分配和释放 - 我可以使用上面链接中描述的 report_memory 函数看到它。但是当我调用 test2 时,内存并没有被释放-report_memory 不断上升。如果我多次调用 test2,我的应用程序会收到内存警告并被终止。
我正在使用ARC。谁能解释这里发生了什么?