سؤال

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?

هل كانت مفيدة؟

المحلول

[[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.

نصائح أخرى

As you suggest, classes are never going to be deallocated by the system, so it hardly matters if you retain them repeatedly and never release them. My guess would be that retain on a class does nothing.

You are exposing those methods as static/class methods (the '+' at the front instead of a '-' for instance methods), so of course you never need to do [[MyClass alloc] init] for this particular class if you only want to use those methods. Since you're not using alloc, you don't have to worry about retain or release.

These days with ARC (Auto Reference Counting) you mostly don't have to worry about retain and release anyway, it adds all that at compile time for you.

EDIT: stressed mostly, as there are times when you still need worry about it, also added some clarity

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top