Search code examples
iosobjective-csingletonretaincountretain-cycle

Class retain counts


Plenty is posted here about avoiding retain cycles with blocks, but what about when using classes and class methods? Say I have a class like this:

// MyClass.h

+ (void)doSomethingAsynch:(void (^)(void))block;
+ (void)doSomethingElse;

and callers would like to say this:

[MyClass doSomethingAsynch:^{
    [MyClass doSomethingElse];
}

Must the caller declare an unsafe_unretained copy of MyClass? Or is a class like a singleton, which won't increase it's retain count? Does it matter if we send a class's retain count to the moon since we want it to exist all the time anyway?


Solution

  • [[NSObject class] retainCount] returns NSUIntegerMax, so, yes, classes are implemented as singletons and probably override release as a no-op.

    Addendum:

    In the objc runtime implementation of NSObject at line 1659 you find ...

    + (id)retain {
        return (id)self;
    }
    

    ... which verifies that [NSObject retain] does nothing.