ios Swift:如何避免UnsafeMutablePointer.allocate崩溃?

5sxhfpxr  于 2022-12-30  发布在  iOS
关注(0)|答案(1)|浏览(166)

下面是我如何解压缩一个lz 4-decompress数据对象的示例代码:

extension Data {
    var calculatedResult: Data? {
        var result: Data?
        let size = 15_000_000
        let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: size)

        // Write data to buffer
        let resultLength = ... // calculate the length of the result data
        result = Data(bytes: buffer, count: read)
        buffer.deallocate()
        return result
    }
}

不过,最近我一直在崩溃:

日志显示“无法分配内存”:

据我所知,这是由于创建buffer时RAM空间不足造成的。在调用UnsafeMutablePointer<Int8>.allocate()之前,是否有任何方法可以检查RAM是否足够?
先谢了伙计们。

sqxo8psd

sqxo8psd1#

您可以使用ProcessInfo.processInfo.physicalMemory检查可用内存。
试试这个:

extension Data {
    var calculatedResult: Data? {
        var result: Data?
        let size = 15_000_000
        let availableMemory = ProcessInfo.processInfo.physicalMemory
        
        if availableMemory < size {
            return nil
        }

        let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: size)
        result = Data(bytes: buffer, count: read)
        buffer.deallocate()
        return result
    }
}

相关问题