gpt4 book ai didi

objective-c - 为什么这段代码会泄漏内存?

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

我有一些for循环。在此周期中,我提出了一些请求并获取响应文本。在循环结束时,由于某种原因,我使线程休眠几秒钟并继续迭代。 [Vk Friends] 中有大约 500 个对象,因此 for 重复大约 500 次,但是当它完成时,我的程序使用的内存比启动时多得多。我使用 ARC,我不明白为什么循环中分配的内存不会在每次迭代时释放?这是正常现象还是我错了?

for (Friend *friend in [Vk friends]) {
[[NSNotificationCenter defaultCenter] postNotificationName:@"log" object:[NSString stringWithFormat:@"Visit %i/%i friend (earn %i coins)", ++count, [Vk friends].count, [UserState coins] - coinsBefore]];
if (friend.helpPoints <= 0) continue;
strData = [NSString stringWithFormat:@"someparams=somevalues&param1=%@", [Vk authKey]];
data = [strData dataUsingEncoding:NSUTF8StringEncoding];
request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://someaddress/somepath?somegetparams=%@", [Vk userId]]]];
request.HTTPMethod = @"POST";
[request setValue:[NSString stringWithFormat:@"%i", [data length]] forHTTPHeaderField:@"Content-Length"];
[request setValue:@"User-Agent Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.43 Safari/536.11" forHTTPHeaderField:@"User-Agent"];
[request setValue:@"http://blahblah.com" forHTTPHeaderField:@"Origin"];
[request setValue:@"http://blahblah.com" forHTTPHeaderField:@"Referer"];
[request setValue:@"ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4" forHTTPHeaderField:@"Accept-Language"];
[request setValue:@"windows-1251,utf-8;q=0.7,*;q=0.3" forHTTPHeaderField:@"Accept-Charset"];
[request setHTTPBody:data];
data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
doc = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
[NSThread sleepForTimeInterval:(helpTimeout + randDouble(min, max)) * 5.0];
}

最佳答案

完全正常。如果您觉得积累了太多内存,请将 for 循环的内部包装在 @autoreleasepool 中,以便它在每次循环迭代结束时回收内存。

关于objective-c - 为什么这段代码会泄漏内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11299908/

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