I want to write an extension for NSDictionary
, so I can easily create it from the data. I wrote it like this:
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 }
}
}
Can't find out why this leaks. Any ideas?
In my case it turned out that the problem was in the latter usage of this dictionary when I tried to get subdictionary from it. To be exact in this code:
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)
}
The problem was that I received geometryDictionary and locationDictionary references without specifying their type, so compiler assumed they are AnyObject. I still was able to get their value like from dictionary so the code worked. When I added the type to them, the leaks stopped.
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With