0

Instruments shows that these lines of code cause memory leaks, what am I doing wrong?

   required init(data: JSON) {
        self.type = data["type"].stringValue
        self.name = data["name"].stringValue
        self.numberOfRestaraunts = data["length"].intValue
        self.isFavourited = data["isFavourited"].boolValue
        self.image = URL(string: data["img"].stringValue)! //<- this
        self.id = data["id"].stringValue
        self.headerImage = URL(string: data["header"].stringValue)! //<- this
        if data["colorSchema"].stringValue == "Dark" {
            self.colorTheme = .dark
        } else {
            self.colorTheme = .light
        }
        self.color = data["color"].stringValue
        self.metaScore = data["metaScore"].intValue
        self.typeMetaScore = data["typeMetaScore"].int ?? 0
    }

It actually shows, that leaks are NSURL class.

EDIT: Screenshots:

enter image description here enter image description here

JuicyFruit
  • 2,638
  • 2
  • 18
  • 35

2 Answers2

0

You are force unwrapping the optional objects. Try to change the line self.image = URL(string: data["img"].stringValue)! to

if let url = URL(string: data["img"].stringValue) {
   self.image = url
}

and this self.headerImage = URL(string: data["header"].stringValue)! line to

if let url = URL(string: data["header"].stringValue) {
   self.headerImage = url
}

Force unwrapping is not a good practice, you should avoid it when possible. Hope this helps!

Fahri Azimov
  • 11,470
  • 2
  • 21
  • 29
  • still leaks, in `if let` line – JuicyFruit Mar 10 '17 at 13:13
  • I don't agree that using force unwrapping is bad practice. If you are sure that in specific situation object must always not be nil, then I would user force unwrapping over optional unwrapping. That is because if later I get error in this place in code, I know that something is wrong with code logic - because I assume that there must not be nil, then when it appears it's better to get an error - then you know that you need to find out why it's not. In any other situation, when optional could be nil, you should use optional unwrapping, but if you are sure - use force. – Damian Dudycz Jul 11 '18 at 13:38
  • I'm not talking about this situation - but about overall practice. – Damian Dudycz Jul 11 '18 at 13:39
0

Could you try this?

if let image_url = URL(string: data["img"].stringValue)
{
    self.image = image_url
}

...and this too...

if let header_url = URL(string: data["header"].stringValue)
{
    self.headerImage = image_url
}

Could you chech if JSON type subscript returns an Optional?

Adolfo
  • 1,862
  • 13
  • 19