【问题标题】:Swift leaks when using NSJSONSerialization使用 NSJSONSerialization 时 Swift 泄漏
【发布时间】:2016-07-31 17:33:30
【问题描述】:

我想为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 }
    }
}

无法找出泄漏的原因。有什么想法吗?

【问题讨论】:

  • 解释你所说的泄漏是什么意思
  • 你说得对,我团队的某个人刚刚在我们正在开发的应用上运行了一个分析器,发现了一个类似的问题

标签: swift memory-leaks nsjsonserialization


【解决方案1】:

在我的情况下,当我试图从中获取子词典时,问题出在这本词典的后一种用法上。确切地说,在这段代码中:

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)
}

问题是我收到了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)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-19
    • 2016-11-18
    • 2020-08-02
    • 1970-01-01
    • 2015-08-20
    • 2016-03-28
    • 2020-04-29
    相关资源
    最近更新 更多