上QQ阅读APP看书,第一时间看更新
How to do it...
- Create two classes, Person and Dog, with a relation between them, as shown in the following code snippet (this code snippet has a memory issue called reference cycle):
class Dog{ var name: String var owner: Person! init(name: String){ self.name = name } } class Person{ var name: String var id: Int var dogs = [Dog]() init(name: String, id: Int){ self.name = name self.id = id } } let john = Person(name: "John", id: 1) let rex = Dog(name: "Rex") let rocky = Dog(name: "Rocky") john.dogs += [rex, rocky] // append dogs rex.owner = john rocky.owner = john
- Update the reference type of owner property in the Dog class to break this cycle:
class Dog{ var name: String weak var owner: Person! init(name: String){ self.name = name } }