将数组指针传递给另一个 Class 并为将来保留一个参考 - Swift

Pass array pointer to another Class and keep a reference for future - Swift

我已成功通过引用传递数组。但是,我想保留引用,以便我可以在另一个 class.

中管理数组

Subclass解析并使用 NSManaged 如下:

class User: PFUser {
    // MARK: Managed Properties
    @NSManaged private var pets: [Pet]

    // MARK: Properties
    private(set) lazy var petList: PetList = PetList(user: self, pets: &self.pets)

    // non-essentials are omitted
}

还有宠物清单class:

class PetList {
    private         var owner: User
    private(set)    var pets: [Pet]

    init(user: User, inout pets: [Pet]) {
        self.owner = user
        self.pets = pets
    }

    func appendPet(pet: Pet) {
        pet.owner = self.owner
        self.pets.append(pet)
    }

}

在 init 函数中,我试图获取对数组的引用。从那里我想修改 PetList class 中的数组(例如 appendPet.

如何在 PetList class 中设置一个变量,使其指向 User class.

中的一个数组

解决 swift 问题的适当方法是使用 extension 到 class 将所有 Pet 相关函数添加到 User class.

最简单的方法是计算属性(如果它应该对主人的宠物进行操作):

class PetList {
    private         var owner: User
    private(set)    var pets: [Pet] {
        get{ return owner.pets }
        set{ owner.pets = newValue }
    }

    init(user: User) {
        self.owner = user
    }

    func appendPet(pet: Pet) {
        pet.owner = self.owner
        self.pets.append(pet)
    }

}

但这对于许多宠物来说可能会很慢,因为每次改变数组时都会设置主人的宠物。

另一种方法是将数组包装在 class:

class ArrayWrapper<T> {
    var array: [T]
    init(_ array: [T]) {
        self.array = array
    }
}

然后只使用包装器而不是数组:

class User: PFUser {
    // MARK: Managed Properties
    @NSManaged private var pets: ArrayWrapper<Pet>

    // MARK: Properties
    private(set) lazy var petList: PetList = PetList(user: self, pets: self.pets)

    // non-essentials are omitted
}

class PetList {
    private         var owner: User
    private(set)    var pets: ArrayWrapper<Pet>

    init(user: User, pets: ArrayWrapper<Pet>) {
        self.owner = user
        self.pets = pets
    }

    func appendPet(pet: Pet) {
        pet.owner = self.owner
        // operate only though the wrapper with .array
        self.pets.array.append(pet)
    }

}

旁注:您可能应该使变量 owner weakunowned 以避免引用循环。