【问题标题】:Hide something in all objects of the same class在同一类的所有对象中隐藏某些内容
【发布时间】:2017-07-13 13:10:38
【问题描述】:

我试图在我的应用程序中同一类的每个对象 (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

在这种情况下最好的(适当的)解决方案是什么?

非常感谢

【问题讨论】:

  • 尝试从查看和隐藏中获取所有标签!请检查下面的链接,这是从视图中获取所有文本字段的示例,但您可以将 UITextField 替换为 UILabel - stackoverflow.com/questions/40908471/…
  • 没有任何神奇的方法可以在不引用这些实例的情况下对类的所有实例进行操作。您可以让您的类实例观察 NSNotification 并在发布该通知时隐藏标签。
  • 好的,但是如果我有多个标签,我只想隐藏一种标签怎么办?
  • “一种标签”是什么意思?

标签: ios objective-c oop static-methods


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多