我有一個使用NSJSONSerialization.JSONObjectWithData
的函數,但是一些內存沒有被釋放。 所以我就找到了泄漏發生的位置,並具有以下功能進行了測試:NSJSONSerialization.JSONObjectWithData泄漏內存
private func test() {
for var i = 0; i < 100000; i++ {
let toParse = NSString(string: "{ \"Test\" : [ \"Super mega long JSON-string which is super long because it should be super long because it is easier to see the differences in memory usage with a super long JSON-string than with a short one.\" ] }").dataUsingEncoding(NSUTF8StringEncoding)!
let json = try! NSJSONSerialization.JSONObjectWithData(toParse, options: NSJSONReadingOptions(rawValue: 0))
}
}
我的應用程序之前,我叫test()
爲11 MB的內存使用率,內存使用率後爲74.4 MB(即使我在我的應用中做了一些其他的事情,給系統一些時間來釋放內存)...
爲什麼json
沒有發佈?
芒迪指出我autoreleasepool
我還沒有試過(插入捂臉這裏)......所以我改變了代碼:
autoreleasepool {
self.test()
}
這並沒有什麼差別,並因爲Xcode中提出的建議,我也試過:
autoreleasepool({() ->() in
self.test()
})
但是,這也沒有工作......
P.S .:也許我應該補充一點,我在Xcode 7 GM
中使用Swift 2.0
。
PPS:該test()
功能全是由內
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), {
//... my code ...
self.test()
})
稱爲但這不應有任何區別...
是啊,我也知道這一點,但我認爲應用測試離開後,它會釋放內存()......它沒」如果我使用你的代碼,它可以工作;但我不明白爲什麼它在測試後不工作()。 並且:謝謝 –