Hi there,
this is my first thread in this forum.
I did the following introduction to memory management, but unfortunately it is not deallocating the the objects as expected (given in the tut).
May you can help and I made a mistake.
https://www.raywenderlich.com/959-arc-and-memory-management-in-swift
MY CODE:
//Why isn’t it deallocating as expected
class User {
var name: String
private(set) var phones: [Phone] = []
var subscriptions: [CarrierSubscription] = []
func add(phone: Phone) {
phones.append(phone)
phone.owner = self
}
init(name: String) {
self.name = name
print("User \(name) is initialized")
}
deinit {
print("User \(name) is being deallocated")
}
}
class Phone {
let model: String
weak var owner: User?
var carrierSubscription: CarrierSubscription?
func provision(carrierSubscription: CarrierSubscription) {
self.carrierSubscription = carrierSubscription
}
func decommission() {
self.carrierSubscription = nil
}
init(model: String) {
self.model = model
print("Phone \(model) is initialized")
}
deinit {
print("Phone \(model) is being deallocated")
}
}
class CarrierSubscription {
let name: String
let countryCode: String
let number: String
unowned let user: User
lazy var completePhoneNumber: () -> String = {
self.countryCode + " " + self.number
}
init(name: String, countryCode: String, number: String, user: User) {
self.name = name
self.countryCode = countryCode
self.number = number
self.user = user
user.subscriptions.append(self)
print("CarrierSubscription \(name) is initialized")
}
deinit {
print("CarrierSubscription \(name) is being deallocated")
}
}
do {
let user1 = User(name: “John”)
let iPhone = Phone(model: “iPhone 6s Plus”)
user1.add(phone: iPhone)
let subscription1 = CarrierSubscription(name: “TelBel”, countryCode: “0032”, number: “31415926”, user: user1)
iPhone.provision(carrierSubscription: subscription1)
print(subscription1.completePhoneNumber())
}
OUTPUT:
User John is initialized
Phone iPhone 6s Plus is initialized
CarrierSubscription TelBel is initialized
0032 31415926
Now that I have added weak to the owner property it should be deallocated. But its not?
Am I missing something?
Thank you for your help!