使用NSJSONSerialization时Swift泄漏

Dam*_*ycz 5 memory-leaks nsjsonserialization swift

我想写一个扩展名NSDictionary,所以我可以轻松地从数据中创建它.我这样写的:

extension Dictionary {
    init?(data: NSData?) {
        guard let data = data else { return nil }
        // TODO: This leaks.
        if let json = (try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions())) as? Dictionary {
            self = json
        }
        else { return nil }
    }
}
Run Code Online (Sandbox Code Playgroud)

无法找出泄漏的原因.有任何想法吗?

Dam*_*ycz 6

在我的例子中,当我试图从中获取子字典时,事实证明问题出现在后者的使用中.准确地说,在这段代码中:

var location: CLLocation? = nil
if let geometryDictionary = json["geometry"], locationDictionary = geometryDictionary["location"], latitude = locationDictionary["lat"] as? CLLocationDegrees, longitude = locationDictionary["lng"] as? CLLocationDegrees {
    location = CLLocation(latitude: latitude, longitude: longitude)
}
Run Code Online (Sandbox Code Playgroud)

问题是我收到了geometryDictionary和locationDictionary引用而没有指定它们的类型,所以编译器假设它们是AnyObject.我仍然可以从字典中获取它们的值,因此代码可以工作.当我向他们添加类型时,泄漏就停止了.

var location: CLLocation? = nil
if let geometryDictionary = json["geometry"] as? [String : AnyObject], locationDictionary = geometryDictionary["location"] as? [String : AnyObject], latitude = locationDictionary["lat"] as? CLLocationDegrees, longitude = locationDictionary["lng"] as? CLLocationDegrees {
    location = CLLocation(latitude: latitude, longitude: longitude)
}
Run Code Online (Sandbox Code Playgroud)