Swift 4通过值复制对象数组,其中包含数组

时间:2019-01-09 17:37:42

标签: arrays swift copy nscopying

我试图了解copy()函数在Swift 4中的工作方式。我有两个类,其结构如下:

class Project {
    var id: Int
    var name: String
    var team: [Person]?

    init(id: Int, name: String, team: [Person]?) {
        self.id = id
        self.name = name
        self.team = team
    }
}

class Person {
    var id: Int
    var name: String
    var project: Project?

    init(id: Int, name: String, project: Project?) {
        self.id = id
        self.name = name
        self.project = project
    }
}

在我的程序中,我有一个项目数组,而我想做的是通过以下方式在数组中创建值的副本:

// arrProjects is some array of projects.
let projectsCopy = arrProjects.map { $0.copy() } as! [Project]

为此,我已经通过以下方式对这两个类实现了NSCopying协议:

extension Project: NSCopying {
    public func copy(with zone: NSZone? = nil) -> Any {
        let teamCopy = self.team?.map { $0.copy() } as! [Person]?
        return Project(id: self.id, name: self.name, team: teamCopy)
    }
}

extension Person: NSCopying {
    public func copy(with zone: NSZone? = nil) -> Any {
        let projectCopy = self.project?.copy() as! Project?
        return Person(id: self.id, name: self.name, project: projectCopy)
    }
}

但是,当我运行代码并运行arrProjects.map { $0.copy() }时,该应用程序将冻结,好像它正在循环,并且在Thread 1: EXC_BAD_ACCESS (code=2, address=0x7ffee5a61ff8)行中抛出了let teamCopy = self.team?.map { $0.copy() } as! [Person]?错误。

知道我要去哪里哪里吗?

1 个答案:

答案 0 :(得分:0)

您不应在public func copy(with zone: NSZone? = nil) -> Any {的定义内使用copy() 您正在创建一个无限循环。

extension Project: NSCopying {
    public func copy(with zone: NSZone? = nil) -> Any {
        let copy = Project(id: self.id, name: self.name, team: self.team)
        return copy
    }
}

extension Person: NSCopying {
    public func copy(with zone: NSZone? = nil) -> Any {
        let copy = Person(id: self.id, name: self.name, project: self.project)
        return copy
    }
}