Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift leaks when using NSJSONSerialization

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?

like image 296
Damian Dudycz Avatar asked Apr 10 '16 18:04

Damian Dudycz


1 Answers

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)
}
like image 107
Damian Dudycz Avatar answered Sep 22 '22 13:09

Damian Dudycz