我想为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 } } }
无法找出泄漏的原因.有任何想法吗?
解决方法
在我的例子中,当我试图从中获取子字典时,事实证明问题出现在后者的使用中.准确地说,在这段代码中:
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],longitude: longitude) }