【问题标题】:Memory issue using ARC in big for loop using NSJSONSerialization使用 NSJSONSerialization 在大 for 循环中使用 ARC 的内存问题
【发布时间】:2016-01-20 16:03:15
【问题描述】:

我目前正在尝试创建一个从 NSString 进行大量 json 序列化的函数。

NSArray* array = nil;
NSError* error = nil;
for (NSObject* obj in otherArray) { 
    array = [NSJSONSerialization JSONObjectWithData:[obj.json dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&error];

    // I'm using array here .. and then i don't need it anymore
}

这里我的 otherArray 可能非常大,而且 obj.json 也是。

但一段时间后,由于内存问题 (> 1GB),应用程序崩溃了。 似乎我的数组在 for 循环中永远不会被释放,因为当我评论该行时,我没有收到任何错误.. 如何使用 ARC 释放内存?

谢谢

【问题讨论】:

    标签: objective-c for-loop memory nsarray nsjsonserialization


    【解决方案1】:

    在循环内使用自动释放池块来减少程序的内存占用:

    NSArray* array = nil;
    NSError* error = nil;
    for (NSObject* obj in otherArray) { 
        @autoreleasepool {
            array = [NSJSONSerialization JSONObjectWithData:[obj.json dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&error];
    
            // I'm using array here .. and then i don't need it anymore
        }
    }
    

    许多程序会创建自动释放的临时对象。这些 对象添加到程序的内存占用,直到结束 堵塞。在许多情况下,允许临时对象堆积 直到当前事件循环迭代结束不会导致 过多的开销;但是,在某些情况下,您可以创建一个 大量增加内存的临时对象 足迹,并且您希望更快地处理。在这些 后一种情况,您可以创建自己的自动释放池块。在 在块的末尾,临时对象被释放,这通常 导致它们被释放,从而减少程序的内存 足迹。

    https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmAutoreleasePools.html#//apple_ref/doc/uid/20000047-SW2

    【讨论】:

    • 我刚刚阅读了有关@autorealeasepool 块的苹果文档,我认为这是解决我的问题的完美解决方案!谢谢!
    • 不客气。请不要忘记接受我的回答,谢谢:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-18
    • 2022-01-07
    相关资源
    最近更新 更多