我对ARC
引用计数有点困惑,你能告诉我下面代码的引用计数是多少吗?
var vc1 = UIViewController()
var vc2 = vc1
var vc3 = vc2
weak var vc4 = vc3
的问题是:将是什么
发布于 2016-11-25 14:51:36
这里,vc1
、vc2
、vc3
指的是同一个对象。因此,该对象引用计数为3。当vc4
引用同一对象时,由于它是弱引用,因此引用计数不会递增1。因此,这之后的引用计数也将为3
vc1
创建并引用的UIViewController
对象的引用计数为1。var vc1:UIViewController?= UIViewController() // strong引用vc2
后的
vc2
相同的对象。对象引用计数变为2var vc2: object vc3
?= vc1 // strong reference
vc3
指的是与vc1
和vc2
相同的对象。对象引用计数变为3var vc3:UIViewController?= vc2 // reference
vc4
和vc1
、vc2
、vc3
指的是同一个对象。由于vc4
是弱引用,因此引用计数不会递增。这意味着计数仍然是3。弱var vc4:UIViewController?= vc3 //弱引用
它的含义:
执行以下代码。
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
here已经讨论了CFRetainCount
在第一行给出2的原因。感谢@CodaFi和@Sahil在评论中的讨论
发布于 2016-11-25 15:01:54
您可以使用CFGetRetainCount函数检查引用计数。
var vc1 = UIViewController()
var vc2 = vc1
var vc3 = vc2
weak var vc4 = vc3
print(CFGetRetainCount(vc1)) //4
print(CFGetRetainCount(vc2)) //4
print(CFGetRetainCount(vc3)) //4
print(CFGetRetainCount(vc4)) //4
您还可以参考此Get Ref Count
发布于 2016-11-25 15:01:50
在我看来,vc1 to vc3会增加保留计数,在我们将strong
指定为weak
之前,by 默认属性是weak
。
Strong :类通常使用Strong来建立对象的所有权。它增加了保留计数( ARC为你处理的东西),它基本上将指向的对象保留在内存中,直到那个类实例停止指向它。这通常是您想要的,但在某些情况下,它会导致所谓的“保留周期”。
在您将其定义为weak
时使用vc4
弱:这会给出一个指向对象的指针,但不会声明所有权,也不会增加保留计数。只要另一个类强烈地指向一个对象,它基本上就会保留一个有效的对象指针。如果没有其他东西试图保留它,弱指针会自动设置为空。
https://stackoverflow.com/questions/40799211
复制相似问题