IOS loops on object properties and adds actions

I have a class with several similar properties - UISliders, and I would like to add actions when the user starts and stops using each slider. Each slider will be associated with the same selector, so I thought to just iterate over them instead of writing 10 nearly identical blocks of code.

The question is, what's the most efficient way to do this? I tried something like this: Loop through all the properties of the object at runtime but the problem is that I cannot call addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents

to objc_property_t property

. Should I just insert properties into the array and iterate over them?

+3


source to share


1 answer


If you don't need a level of agility that involves checking your object's properties at runtime, this NSArray

is the simplest and most straightforward way; as far as I am suggesting making a dynamic array of type void *

and iterating over it might be faster, but for you it will run at questionable speed given the typical sizes.

for (UISlider *slider in @[self.slider1, self.slider2, self.slider3]) {
    [slider addTarget:self action:@selector(action:) forControlEvents:UIControlEventValueChanged];
}

      



If you need to research your properties, I would get very close to it, as the answer to another question suggested. My answer first suggested parsing the property attribute string to account for custom name properties, but apparently KVC will take care of that for you.

unsigned int numberOfProperties;
objc_property_t *properties = class_copyPropertyList([self class], &numberOfProperties);
for (int i = 0; i < numberOfProperties; i++) {
    objc_property_t property = propertieses[i];
    NSString *propertyName = [NSString stringWithUTF8String:property_getName(property)];
    id valueForProperty = [self valueForKey:propertyName];
    if ([valueForProperty isKindOfClass:[UISlider class]]) {
        [(UISlider *)valueForProperty addTarget:self 
                                         action:@selector(action:) 
                               forControlEvents:UIControlEventValueChanged];
    }
}
free(properties);

      

+4


source







All Articles