【发布时间】:2021-10-09 22:16:15
【问题描述】:
我目前正在测试我从 Android 移植到 iOS 的流媒体应用程序,在耐久性测试期间,我注意到一个小的内存泄漏,我终于能够找到它。唯一的问题是我不明白它为什么会发生。我对 Swift 比较陌生,所以这可能很明显,但也许有人可以解释一下。您可以在下面找到如何重现内存泄漏的示例
private class TestThread: Thread {
override func main() {
self.name = "TestThread"
print("Started TestThread")
repeat {
let frameSize = Int.random(in: 523..<63453)
let dataBuffer = UnsafeMutableRawPointer.allocate(byteCount: frameSize, alignment: MemoryLayout<UInt8>.alignment)
let frameData = Data(bytesNoCopy: dataBuffer, count: frameSize, deallocator: .none)
// The line below works fine, no memory leak
//dataBuffer.deallocate()
// Using the code below instead of the line above will result in a memory leak
let pointer = (frameData as NSData).bytes
pointer.deallocate()
ThreadingUtil.sleep(ms: 5)
} while !isCancelled
}
}
// This is the ThreadingUtil.sleep method
public static func sleep(ms: UInt) {
usleep(useconds_t(1000 * ms))
}
当您创建并启动 TestThread 时,您可以观察到内存随着时间的推移略有增加,并且只有在您停止线程后才会被垃圾回收。似乎缓冲区内存的大部分可以被垃圾收集,但仍有一小部分。我想知道为什么当我解除分配原始的 UnsafeMutableRawPointer 'dataBuffer' 时它可以正常工作?
【问题讨论】:
标签: ios swift iphone memory-leaks swift5