Reputation: 690
I'm trying to hide a UILabel in every object (UIView) of the same class in my app. I tried something with a static class method but I'm not able to access to the instance variable.
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
What is the best (proper) solution in this kind of situation?
Thank you very much
Upvotes: 0
Views: 94
Reputation: 16774
For your case I suggest you to have references to all of this objects. This means you will need to add the object into some static array in its constructor.
The problem then occurs that the views will be retained by the array so you need another object that will be a container for a weak reference to your object so you avoid memory leak.
Try to build something like the following:
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
Upvotes: 1