【问题标题】:Why isUniquelyReferencedNonObjC returns false in this case?为什么 isUniquelyReferencedNonObjC 在这种情况下返回 false?
【发布时间】:2016-03-02 00:41:03
【问题描述】:

我正在研究 Swift 中引用计数的工作原理。在下面的 sn-p 中,我实例化了一个全新的 Person 对象并检查它是否被唯一引用。我相信它是唯一引用的,因为它只保留在“人”实例上。但是,isUniquelyReferencedNonObjC 函数返回 false。

谁能解释这是为什么?

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    var person = Person()

    // this will output not unique
    if isUniquelyReferencedNonObjC(&person) {
        println("unique")
    } else {
        println("not unique")
    }

    return true
}

人物类:

class Person: NSObject {

}

编辑 有趣的是,当我不将 Person 设为 NSObject 的子类时,isUniquelyReferencedNonObjC 将按预期返回 true。但是,我仍然不明白为什么继承 NSObjct 会在这里有所作为。

提前致谢。

【问题讨论】:

  • 你能告诉我们Person类吗?

标签: ios swift memory-management automatic-ref-counting


【解决方案1】:

isUniquelyReferencedNonObjC 记录为

/// Returns `true` iff `object` is a non-\ `@objc` class instance with
/// a single strong reference.
/// ...
/// * If `object` is an Objective-C class instance, returns `false`.
/// ...

您的Person 类继承自NSObject,因此 isUniquelyReferencedNonObjC(&person) 返回false

【讨论】:

猜你喜欢
  • 2018-04-26
  • 1970-01-01
  • 2014-09-12
  • 2018-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多