Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isUniquelyReferencedNonObjC returns false in this case?

I'm investigating how reference counting works in Swift. In the following snippet I instantiated a brand new Person object and check whether it's uniquely referenced. I believed it is uniquely referenced since it only retains on the "person" instance. However, isUniquelyReferencedNonObjC function returns false.

Can anyone explain why this is?

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
}

Person class:

class Person: NSObject {

}

EDIT Interestingly when I don't make Person a subclass of NSObject then isUniquelyReferencedNonObjC will return true as expected. However, I still don't understand why subclassing NSObjct will make a difference here.

Thanks in advance.

like image 692
Roy Li Avatar asked Nov 27 '15 19:11

Roy Li


1 Answers

isUniquelyReferencedNonObjC is documented as

/// 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`.
/// ...

Your Person class inherits from NSObject, therefore isUniquelyReferencedNonObjC(&person) returns false.

like image 104
Martin R Avatar answered Nov 15 '22 05:11

Martin R