In Objective-c how can we have a variable whose scope is the whole class (but doesn't include subclasses)

前端 未结 2 1813
南方客
南方客 2021-01-26 00:25

I created tons of subclasses of UITableViewCell. Each of which is a subclass of an additional BGBaseTableViewCell class.

When asked for height, I think it\'ll be useful

相关标签:
2条回答
  • 2021-01-26 01:16

    Why didn't I think of it.

    Make the static variable a dictionary and set the class names as the keys :)

    Ladies and gentlemen, children of all ages. Sharen Eayrs production proudly presents, statically protected variables:

    static NSMutableDictionary * defaultHeightDictionary= nil;
    static NSMutableDictionary * defaultBoundsDictionary =nil;
    //static CGFloat defaultHeightSet = 0;
    
    +(void)initialize
    {
        BGBaseTableViewCell * typical = [[self alloc]init];
    
        if (defaultHeightDictionary==nil) {
            defaultHeightDictionary = [NSMutableDictionary dictionary];
            defaultBoundsDictionary = [NSMutableDictionary dictionary];
        }
        [defaultHeightDictionary setValue:@(typical.bounds.size.height) forKey:NSStringFromClass([self class])];
        CGRect bounds = typical.bounds;
    
        NSValue * boundsValue = [NSValue valueWithCGRect:bounds];
        [defaultHeightDictionary setValue:boundsValue forKey:NSStringFromClass([self class])];
    
    
    }
    +(CGFloat) defaultHeight
    {
        NSNumber * result = [defaultHeightDictionary valueForKey:NSStringFromClass([self class])];
        return result.floatValue;
    }
    
    +(CGRect) defaultBounds
    {
        NSValue * result = [defaultBoundsDictionary valueForKey:NSStringFromClass([self class])];
        return [result CGRectValue];
    }
    
    0 讨论(0)
  • 2021-01-26 01:28

    Visible in whole class but not for subclasses? You can try this code for your .m file:

    @interface ClassYouNeed ()
    static VariableClass* variableVisibleInClassButNotInSubclass;
    @end
    

    Just make a "hidden" category on your class near your implementation, it should work.

    0 讨论(0)
提交回复
热议问题