@autoreleasepool 似乎没有耗尽池

@autoreleasepool does not seem to drain pool

我在大型应用程序中遇到内存问题。我已将其简化为以下代码。如果我让应用程序 运行 完成,内存就会耗尽,因此我没有真正的内存泄漏。

但是,由于它是 运行,每次调用 customLog: 都会累积内存,而内存不会耗尽。所以我添加了一个 @autoreleasepool 块来包装对 log: 的调用,它似乎仍然没有耗尽。有没有可能我没有正确使用@autoreleasepool?

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {

    // Insert code here to initialize your application

    for (int i=0; i<100000; i++) {
        [Logger customLog:[NSString stringWithFormat:@"%i", i]];
    }

    for (int i=0; i<100000000; i++) {
        NSLog(@"X%i", i);
    }
}

记录器class:

- (void)customLog:(NSString *)logString
{
    @autoreleasepool {
        [self log:[[NSString alloc] initWithFormat:@"%@ %@:%d\t\t%s\t\%@", [[NSDate  date] descriptionWithCalendarFormat:@"%Y-%m-%d %H:%M:%S.%F" timeZone:nil locale:[[NSUserDefaults standardUserDefaults] dictionaryRepresentation]], [[NSString stringWithUTF8String:__FILE__] lastPathComponent], __LINE__, __FUNCTION__, logString]];
    }
}

自动释放池在错误的位置。您只清除在 @autoreleasepool 中创建的任何自动释放的对象。但是您在自动释放池之外创建了数千个 NSString 临时对象,因此在对 applicationDidFinishLaunching: 的调用完成之前不会清理这些对象。

尝试:

for (int i=0; i<100000; i++) {
    @autoreleasepool {
        [Logger customLog:[NSString stringWithFormat:@"%i", i]];
    }
}

并删除 customLog: 方法中的 @autoreleasepool