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:
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!
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
?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.