ios - ARC 中的引用计数

标签 ios objective-c swift automatic-ref-counting

我对 ARC 的引用计数有点困惑,你能告诉我波纹管代码的引用计数是多少吗?

var vc1 = UIViewController()
var vc2 = vc1
var vc3 = vc2
weak var vc4 = vc3

问题是:

  • vc1 的引用计数 ?
  • vc2 的引用计数 ?
  • vc3 的引用计数 ?
  • vc4 的引用计数 ?

最佳答案

这里,vc1vc2vc3指的是同一个对象。所以,那个对象的引用计数是3。当vc4引用同一个对象时,由于是弱引用,引用计数不会加1。所以,这之后的引用计数会也是3

  1. 第一行代码后vc1创建并引用的UIViewController对象的引用计数为1。

    var vc1:UIViewController? = UIViewController() // strong reference 
    
  2. vc2之后和vc1指的是同一个对象。对象的引用计数变为2

    var vc2:UIViewController? = vc1 // strong reference
    
  3. vc3之后与vc1vc2指的是同一个对象。对象的引用计数变为3

    var vc3:UIViewController? = vc2 // strong reference
    
  4. vc4之后与vc1vc2vc3指的是同一个对象。由于 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/

相关文章:

ios - 按返回后,表格 View 顶部导航栏的空间增加

ios - Scratch的iOS重新设计发布应用

iphone - 如何将 UIImagePickerController 与基于 tabBar 的应用程序一起使用?

ios - 丢失分发的私钥,推送通知

ios - 是否有官方方式在 Apple Watch 和 iPhone 之间传递数据?

objective-c - NSView背景图片由3个不同的文件组成

ios - 仅制作一个 ios tabbar app 纵向选项卡

ios - 如何将数据从 UIViewController 发送到 UITabBarControllers swift ios 中的第一个选项卡

swift - 调用view.removeFromSuperview()后是否需要设置view为nil?

swift - 无需解码即可快速读取 jpeg 的高度宽度和文件大小的方法