内存泄漏_ContiguousArrayStorage?

时间:2017-03-10 07:02:36

标签: ios iphone swift xcode memory-leaks

我是swift的新手。我正在运行内存泄漏的仪器工具。我发现了泄漏"_ContiguousArrayStorage<String>"

Screen Shot of Instruments

它导致了部分代码

let myData = NSData(data: request.value!)
let buffer = Array(UnsafeBufferPointer(start: UnsafePointer<CUnsignedChar>(myData.bytes), count: myData.length))

Screenshot of code leakage lines

任何人都可以帮帮我吗?

以上代码有什么问题吗?

编辑: 添加更多代码。

let myData = NSData(data: request.value!)
var buffer = Array(UnsafeBufferPointer(start: UnsafePointer<CUnsignedChar>(myData.bytes), count: myData.length))

let responseArray: [CUnsignedChar] = Array(buffer)

let responseValue = BluetoothCommunicationManager.sharedInstance.parseData(responseArray,length: myData.length).0

let responseName = BluetoothCommunicationManager.sharedInstance.parseData(responseArray,length: myData.length).1

NSNotificationCenter.defaultCenter().postNotificationName(responseName, object: request, userInfo: responseValue as [NSObject : AnyObject])

singleton类的parseData方法返回NSMutableDictionary。

func parseData(responseData: [CUnsignedChar]) -> NSMutableDictionary
{
        let infoDictionary = NSMutableDictionary()
        let subIndexValue = Int(responseData[5])
        infoDictionary.setValue(subIndexValue, forKey: KEY_SUB_INDEX)
        return responseData
}

提前致谢。

2 个答案:

答案 0 :(得分:1)

您似乎正在尝试将NSData转换为CUnsignedChar数组。您无需使用UnsafeBufferPointerUnsafePointer进行转换。我怀疑你使用不安全的指针是导致内存泄漏的根本原因。

您可以通过传递Data对象而不是NSData对象来创建数组。试试这个:

let myData = NSData(data: request.value!) as Data
let responseArray = [CUnsignedChar](myData)

let responseValue = BluetoothCommunicationManager.sharedInstance.parseData(responseArray, length: responseArray.count).0

let responseName = BluetoothCommunicationManager.sharedInstance.parseData(responseArray, length: responseArray.count).1

答案 1 :(得分:0)

我对一个不是Objective-C和Swift混合的项目有同样的问题。事实证明,字符串插值可能会泄漏内存:

http://www.openradar.me/26761490

TL; DR是将字符串插值更新为字符串连接。

所以:

print("Cannot write to characteristic \(request.characteristic.UUID)")

变为:

print("Cannot write to characteristic " + request.characteristic.UUID)