Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

class method where self if used within a block

I've got a class method that uses dispatch_once to create a static object. Inside the dispatch_once block I use [self class] and was wondering if I need to use a weak reference to self to avoid a retain cycle?

+ (NSArray *)accountNames{
    static NSArray *names = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        names = [[[self class] accounts] allKeys];
        names = [names sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
    });
    return names;
}

If I use a weak reference to self I get a warning:

+ (NSArray *)accountNames{
    static NSArray *names = nil;
    static dispatch_once_t predicate;
    __weak TUAccount *wself = self;
    dispatch_once(&predicate, ^{
        names = [[[wself class] accounts] allKeys];
        names = [names sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
    });
    return names;
}

Incompatible pointer types initializing 'TUAccount *__weak' with an expression of type 'const Class'

Because I get a warning I don't think I need to use a weak reference to self in this case but I wanted to see what you guys thought.

like image 287
keegan3d Avatar asked Jun 05 '12 05:06

keegan3d


1 Answers

There is no reason to worry about a retain cycle here, because it's meaningless to retain or release a class object -- retain and release simply have no effect.

Your attempt at making a weak reference is wrong, because you are taking a class object self and trying to cast it to an instance of TUAccount. The two are completely different things.

Also, you can simplify:

names = [[[self class] accounts] allKeys];

Since self is already a class, [self class] == self, so do this instead:

names = [[self accounts] allKeys];
like image 190
Kurt Revis Avatar answered Oct 15 '22 11:10

Kurt Revis