'自'在所有成员迅速初始化之前被关闭捕获3

时间:2017-11-13 23:46:17

标签: swift asynchronous initialization

这是我目前的代码:

import UIKit

class Pet: NSObject, NSCoding {

// Mark: - Member Variables
public var id: Int?
public var name: String?
public var groupID: Int?
public var breedID: Int?
public var weight: Int?
public var chipNum: Int?
public var imageURL: String?
public var petImage: UIImage?
public var dispatch = DispatchGroup()

init(id: Int, name: String, groupID: Int, breedID: Int, weight: Int, chipNum: Int, imageURL: String) {
    self.id = id
    self.name = name
    self.groupID = groupID
    self.breedID = breedID
    self.weight = weight
    self.chipNum = chipNum
    self.imageURL = imageURL
    self.petImage = UIImage()

    dispatch.enter()
    //line below is causing: 'self' captured by a closure before all members were initialized
    DispatchQueue.global(qos: .default).async {
        // This needs to be async
        if self.imageURL != "" {
            let url: URL = URL(string: self.imageURL!)!
            let imageData: Data = try! Data(contentsOf: url)
            self.petImage = UIImage(data: imageData)
        }
    }
    dispatch.wait()
}

// MARK: - Persist User Data
required convenience init(coder aDecoder: NSCoder) {
    let petID = aDecoder.decodeObject(forKey: "id") as! Int
    let petName = aDecoder.decodeObject(forKey: "name") as! String
    let petGroup = aDecoder.decodeObject(forKey: "groupID") as! Int
    let breedID = aDecoder.decodeObject(forKey: "breedID") as! Int
    let weight = aDecoder.decodeObject(forKey: "weight") as! Int
    let chipNum = aDecoder.decodeObject(forKey: "chipNum") as! Int
    let image = aDecoder.decodeObject(forKey: "image") as! String
    self.init(id: petID, name: petName, groupID: petGroup, breedID: breedID, weight: weight, chipNum: chipNum, imageURL: image)
}

func encode(with aCoder: NSCoder){
    aCoder.encode(self.id, forKey: "id")
    aCoder.encode(self.name, forKey: "name")
    aCoder.encode(self.groupID, forKey: "groupID")
    aCoder.encode(self.breedID, forKey: "breedID")
    aCoder.encode(self.weight, forKey: "weight")
    aCoder.encode(self.chipNum, forKey: "chipNum")
    aCoder.encode(self.imageURL, forKey: "image")
//        aCoder.encode(self.petImage, forKey: "petImage")
    }
}

到目前为止,我尝试过几件不同的事情。我甚至试图将代码从dispatch.enter()移动到另一个函数中的dispatch.wait(),从init调用该函数,然后在新创建的函数调用上面调用super.init()。虽然这编译和运行"该应用程序,它无法通过启动屏幕,并永远陷入启动屏幕。

我看到正在使用的所有变量都已正确初始化,因此我不确定为什么我会收到此错误"' self'在所有成员初始化之前由关闭捕获"

我必须保持对服务器的这个异步调用才能获取图像。虽然它不是异步的,但它是一种非常危险的做法,当与服务器的连接超时时可能会崩溃。

非常感谢任何见解或反馈。谢谢。

0 个答案:

没有答案