Get all instances of a class in objective c?

前端 未结 4 1500
不思量自难忘°
不思量自难忘° 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:26

    First I'd say whatever you're trying to accomplish can likely be better accomplished with NSNotificationCenter, that said, if you still need to do this, the following will work and will be ARC compliant.

    In your .h add this:

    +(NSArray *)allInstances;
    

    Then, add this to the bottom of your class's .m:

    -(id)init {
        //Note, I suppose you may need to account for exotic init types if you are creating instances of your class in non-traditional ways. I see in the docs that initWithType: exists for example, not sure what storyboard calls
        self = [super init];
        [[self class] trackInstance:self];
        return self;
    }
    -(void)dealloc {
        [[self class] untrackInstance:self];
    }
    
    static NSMutableArray *allWeakInstances;
    +(void)trackInstance:(id)instance {
        if (!allWeakInstances) {
            allWeakInstances = [NSMutableArray new];
        }
        NSValue *weakInstance = [NSValue valueWithNonretainedObject:instance];
        [allWeakInstances addObject:weakInstance];
    }
    +(void)untrackInstance:(id)instance {
        NSValue *weakInstance = [NSValue valueWithNonretainedObject:instance];
        [allWeakInstances removeObject:weakInstance];
    }
    +(NSArray *)allInstances {
        NSMutableArray *allInstances = [NSMutableArray new];
        for (NSValue *weakInstance in allWeakInstances) {
            [allInstances addObject:[weakInstance nonretainedObjectValue]];
        }
        return allInstances.copy;
    }
    

    Then when you need all instances of the class, just call [Class allInstances];

提交回复
热议问题