Fast leak when using NSJSONSerialization

I want to write an extension for NSDictionary , so I can easily create it from data. I wrote this as follows:

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

I can’t understand why this is happening. Any ideas?

+5
source share
1 answer

In my case, it turned out that the problem was the last use of this dictionary when I tried to get subtasks 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 got the geometryDictionary and locationDictionary links without specifying their type, so the compiler suggested that they are AnyObject. I could still get my value from a dictionary, so the code worked. When I added a 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) } 
+6
source

Source: https://habr.com/ru/post/1246825/


All Articles