gpt4 book ai didi

iphone - NSString stringWithFormat 调用 XX 次导致内存警告

转载 作者:行者123 更新时间:2023-12-03 21:03:06 25 4
gpt4 key购买 nike

我开始使用此处描述的技术来监视应用程序内存使用情况: 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。谁能解释一下这里发生了什么?

最佳答案

stringWithFormat 返回一个自动释放的 NSString 对象。这样,当该线程结束时释放自动释放池时,该对象就会被释放。

关于iphone - NSString stringWithFormat 调用 XX 次导致内存警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12562282/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com