NSProgress带来巨大的内存增长

时间:2016-02-13 22:42:39

标签: ios swift nsprogress

我正在尝试使用NSProgress,在后台线程上找到一个简单的循环会导致内存快速增长:

class Worker {
    var progress:NSProgress?

    func doWork() {
        let numIterations:Int64 = 100000
        let delay:UInt32 = 100

        let progressObj = NSProgress(totalUnitCount: numIterations)
       // progressObj.cancellable = true
        progress = progressObj


        let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT

        dispatch_async(dispatch_get_global_queue(priority, 0)) {
            progressObj.becomeCurrentWithPendingUnitCount(numIterations)
            for i in 0...numIterations {
                progressObj.completedUnitCount = i
                usleep(delay)
            }

            progressObj.resignCurrent()
        }

    }

}

使用Allocations工具进行分析显示内存在30秒内增长到大约20mb(如果我增加循环的大小,则更多)。分配全部归因于_NSProgressFraction

有什么明显的东西我会忽略,或者这是NSProgress的错误吗?

1 个答案:

答案 0 :(得分:4)

经过一些实验后,看起来设置progressObj.completedUnitCount的行为会导致NSProgress对当前的自动释放池进行分配。我发现通过将循环体包装在自动释放池中,我可以防止内存增长,如下所示:

for i in 0...numIterations {
    autoreleasepool {
        progressObj.completedUnitCount = i
        usleep(delay)
    }
}