获取目标c中类的所有实例?

问题描述 投票:2回答:4

我有一个包含许多实例的UIView,每个实例都有一个UIRecognizer。

点击其中一个时,我想删除其他所有识别器。

我想要它获取该类的所有实例并删除其识别的内容。

我知道ManagedObjects具有[Entity allObjects];

如何创建“所有对象”类方法?

objective-c ios class-method
4个回答
5
投票

我有两个想法:

1 /用所有实例static NSArray* instances;创建一个类数组,在初始化时注册它们,在取消分配时注销。该数组应该只有弱引用,否则它们将永远不会被释放。

2 / NSNotification。所有实例都可以等待通知,如果您点击,则发送通知。


0
投票

如果只需要查找所有实例以进行调试,则可以使用Allocations工具并将Recorded Types更改为仅您的类。这将为您提供所有对象的详尽清单。然后,您可以使用lldb通过他们的地址与他们互动。


0
投票

在您的.h中添加此:

+(NSArray *)allInstances;

然后,将其添加到班级.m的底部:

-(id)init {
    self = [super init];
    [[self class] trackInstance:self];
    return self;
}
-(void)dealloc {
    [[self class] untrackInstance:self];
}

static NSMutableArray *allInstances;
+(void)trackInstance:(id)instance {
    if (!allInstances) {
        allInstances = [NSMutableArray new];
    }
    [allInstances addObject:instance];
}
+(void)untrackInstance:(id)instance {
    [allInstances removeObject:instance];
}
+(NSArray *)allInstances {
    return allInstances.copy;
}

然后,当您需要该类的所有实例时,只需调用[Class allInstances];


-1
投票

如果它们都是同一视图的所有子视图,则可以遍历parentView.subviews并以这种方式找到它们。像这样的东西:

for (UIView *v in parentView.subviews) {
    if ([v isKindOfClass:[MyViewClass class]]) {
        // remove recognizer here
    }
}

另一个更有效的选择是在视图控制器中具有一个标志,该标志在触发第一个识别器时设置,并用于使以后的任何识别器处理程序调用短路。像这样的东西:

@property (nonatomic) BOOL shouldRespondToEvent;
@synthesize shouldRespondToEvent=_shouldRespondToEvent;

- (void)viewDidLoad {
    [super viewDidLoad];
    self.shouldRespondToEvent = YES;
    // other viewDidLoad stuff here
}

- (void)gestureHandler:(UIGestureRecognizer*)recognizer {
    if (!self.shouldRespondToEvent)
        return;
    self.shouldRespondToEvent = NO;
    // rest of handler code here
}
© www.soinside.com 2019 - 2024. All rights reserved.