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

时间:2012-07-02 19:23:18

标签: objective-c multithreading macos cocoa for-loop

我有一些循环。在这个循环中,我提出了一些请求并获得了响应文本。在循环结束时,由于某种原因我睡眠线程几秒钟并继续迭代。 [Vk朋友]中有大约500个对象,因此重复大约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];
}

1 个答案:

答案 0 :(得分:5)

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