我对 ARC
的引用计数有点困惑,你能告诉我波纹管代码的引用计数是多少吗?
var vc1 = UIViewController()
var vc2 = vc1
var vc3 = vc2
weak var vc4 = vc3
问题是:
- vc1 的引用计数 ?
- vc2 的引用计数 ?
- vc3 的引用计数 ?
- vc4 的引用计数 ?
最佳答案
这里,vc1
、vc2
、vc3
指的是同一个对象。所以,那个对象的引用计数是3。当vc4
引用同一个对象时,由于是弱引用,引用计数不会加1。所以,这之后的引用计数会也是3
第一行代码后
vc1
创建并引用的UIViewController
对象的引用计数为1。var vc1:UIViewController? = UIViewController() // strong reference
在
vc2
之后和vc1
指的是同一个对象。对象的引用计数变为2var vc2:UIViewController? = vc1 // strong reference
在
vc3
之后与vc1
和vc2
指的是同一个对象。对象的引用计数变为3var vc3:UIViewController? = vc2 // strong reference
在
vc4
之后与vc1
、vc2
和vc3
指的是同一个对象。由于vc4
是弱引用,引用计数不会增加。这意味着计数仍然是 3。weak var vc4:UIViewController? = vc3 // weak reference
含义:
执行以下代码。
vc1 = nil; // reference count = 3-1 = 2
vc2 = nil; // reference count = 2-1 = 1
vc3 = nil; // reference count = 1-1 = 0 and object is destroyed
现在,打印vc4
的值。它将是 nil
。发生这种情况是因为对象的引用计数变为零并且所有变量都引用同一个对象。
编辑:
在下面的代码中使用 CFGetRetainCount
会得到如下结果:
var vc1:NSDate? = NSDate()
print(CFGetRetainCount(vc1)) // 2 - I expected this to be 1 as only one variable is strongly referring this object.
var vc2:NSDate? = vc1
print(CFGetRetainCount(vc1)) // 3 - reference count incremented by 1 (strong reference)
var vc3:NSDate? = vc2
print(CFGetRetainCount(vc3)) // 4 - reference count incremented by 1 (strong reference)
weak var vc4:NSDate? = vc1
print(CFGetRetainCount(vc1)) // 4 - reference count not incremented (weak reference)
vc1 = nil
print(CFGetRetainCount(vc2)) // 3 - reference count decremented by 1 (strong reference removed)
vc2 = nil
print(CFGetRetainCount(vc3)) // 2 - reference count decremented by 1 (strong reference removed)
vc3 = nil
print(vc4) // nil - reference count should be decremented by 1 (last strong reference removed)
// Also due to the final line vc3 = nil, reference count should become zero
// However, we can't use `CFGetRetainCount` to get reference count in this case
// This is due to the final strong reference being removed and object getting destroyed
CFRetainCount
在第 1 行给出 2 的原因已被讨论 here .感谢@CodaFi 和@Sahil 在评论中的讨论
关于ios - ARC 中的引用计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40799211/