URL内存泄漏

时间:2017-03-10 12:19:59

标签: ios swift memory-leaks instruments

仪器显示这些代码行导致内存泄漏,我做错了什么?

   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
    }

它实际上表明,泄漏是NSURL类。

编辑:截图:

enter image description here enter image description here

2 个答案:

答案 0 :(得分:0)

您正在展开可选对象。尝试将行this更改为

self.image = URL(string: data["img"].stringValue)!

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

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

强制展开不是一个好习惯,你应该尽可能避免它。希望这有帮助!

答案 1 :(得分:0)

你可以尝试一下吗?

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

......这也是......

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

如果JSON类型subscript返回Optional,您可以选择吗?

相关问题