为什么在这种情况下,UniquelyReferencedNonObjC返回false?

时间:2015-11-27 19:24:18

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

我正在研究引用计数在Swift中的工作原理。在下面的代码片段中,我实例化了一个全新的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会在这里产生影响。

提前致谢。

1 个答案:

答案 0 :(得分:5)

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

相关问题