Get all instances of a class in objective c?

前端 未结 4 1526
不思量自难忘°
不思量自难忘° 2021-01-15 11:58

I have a UIView that has many instances and each one of them has a UIRecognizer.

When on of them is tapped I want to remove all the recognizers of the others.

<
4条回答
  •  时光取名叫无心
    2021-01-15 12:20

    If they're all subviews of the same view, you could iterate over parentView.subviews and find them that way. Something like this:

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

    Another, more efficient, option would be to have a flag in your view controller that you set when the first recognizer is triggered and use to short-circuit any future recognizer handler calls. Something like this:

    @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
    }
    

提交回复
热议问题