jig*_*iya 19 objective-c ios automatic-ref-counting swift
我在ARC引用计数方面有点混乱你可以告诉我下面的波纹管代码的参考数量.
var vc1 = UIViewController()
var vc2 = vc1
var vc3 = vc2
weak var vc4 = vc3
问题是:
Kri*_*aCA 18
这里vc1,vc2,vc3指的是同一个对象.因此,该对象的引用计数为3.当vc4引用同一对象时,由于它是弱引用,引用计数不会增加1.因此,此后的引用计数也将为3
在第一行代码之后UIViewController创建和引用的对象的引用计数vc1为1.
var vc1:UIViewController? = UIViewController() // strong reference 
之后vc2指的是同一个对象vc1.对象的引用计数变为2
var vc2:UIViewController? = vc1 // strong reference
后vc3指的是相同的对象vc1和vc2.对象的引用计数变为3
var 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讨论了第一行给出2 的原因.感谢@CodaFi和@Sahil在评论中的讨论
| 归档时间: | 
 | 
| 查看次数: | 3065 次 | 
| 最近记录: |