I'm reading about ARC
and being confused about increasing Reference Count
. My example code is below.
My first class:
class Owner{
var name: String
weak var cat:Cat? //Cat reference count will not increase because of 'weak'
init(name: String){
self.name = name
print("Owner class is initialized.")
}
deinit{
print("Owner class is deinitialized.")
}
}
My Second Class:
class Cat{
var name: String
var owner: Owner?
init(name: String){
self.name = name
print("Cat class is initialized.")
}
deinit {
print("Cat class is deinitilized.")
}
}
My Class usage code:
var mamun: Owner? = Owner(name: "Mamun") //OwnerAR = 1
var vutu: Cat? = Cat(name: "Vutu") // CatAR = 1
mamun?.cat = vutu // CatAr = 1
vutu?.owner = mamun // OwnerAR = 2
mamun = nil // OwnerAR = 1
vutu = nil // CatAR = 0
Output:
Owner class is initialized.
Cat class is initialized.
Cat class is deinitilized.
Owner class is deinitialized.
Confution: When Owner
reference count is 1, why it is being deinitialized after vutu = nil
code execution. Am i doing wrong on counting reference?
When you set vutu
to nil
, that object's reference count goes to zero and it gets deinitialized as expected. In the process of getting deinitialized, it releases any strong references to objects it has. So its owner
is released. That brings the reference count to 0 for the object referenced by your mamun
variable. And that is why you see the last message of Owner class is deinitialized.
.
mamun?.cat = vutu // CatAr = 1 (1 by vutu)
vutu?.owner = mamun // OwnerAR = 2 (1 by vutu's owner and another by mamun)
mamun = nil // OwnerAR = 1 (1 by vutu's owner) == cannot deinit until vutu deinit
vutu = nil // CatAR = 0 == vutu deinit == OwnerAR = 0 == mamun deinit
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.