隐藏同一类的所有对象中的某些内容

时间:2017-07-13 13:10:38

标签: ios objective-c oop static-methods

我正在尝试在我的应用中的同一个类的每个对象(UIView)中隐藏UILabel。我尝试了一些静态类方法,但我无法访问实例变量。

MyView.h

@interface MyView: UIView
{
    UILabel *titleLabel;
    UILabel *subTitleLabel;
}

+(void)hideLabel;

@end

MyView.m

#import "MyView.h"

@implementation TempNodeView

    +(void)hideLabel
    {
        [titleLabel setHidden:YES];
    }

@end

在这种情况下,最佳(正确)解决方案是什么?

非常感谢

1 个答案:

答案 0 :(得分:1)

对于您的情况,我建议您引用所有这些对象。这意味着您需要在其构造函数中将对象添加到某个静态数组中。

然后出现问题,数组将保留视图,因此您需要另一个对象作为对象弱引用的容器,以避免内存泄漏。

尝试构建如下内容:

static NSMutableArray *__containersPool = nil;

@interface MyViewContainer : NSObject
@property (nonatomic, weak) MyView *view;
@end

@implementation MyViewContainer
@end

@interface MyView : UIView
@property (nonatomic, readonly) UILabel *labelToHide;
@end

@implementation MyView

+ (NSMutableArray *)containersPool {
    if(__containersPool == nil) {
        __containersPool = [[NSMutableArray alloc] init];
    }
    return __containersPool;
}

// TODO: override other constructors as well
- (instancetype)initWithFrame:(CGRect)frame {
    if((self = [super initWithFrame:frame])) {
        MyViewContainer *container = [[MyViewContainer alloc] init];
        container.view = self;
        [[MyView containersPool] addObject:container];
    }
    return self;
}

+ (void)setAllLabelsHidden:(BOOL)hidden {
    for(MyViewContainer *container in [[self containersPool] copy]) {
        if(container.view == nil) {
            [[self containersPool] removeObject:container]; // It has been released so remove the container as well
        }
        else {
            container.view.labelToHide.hidden = hidden;
        }
    }
}

@end