iOS循环对象的属性并添加操作 [英] iOS looping over an object's properties and adding actions

查看:178
本文介绍了iOS循环对象的属性并添加操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有几个类似属性的类 - UISliders,我想为用户在每个滑块开始和结束时添加操作。每个滑块都链接到同一个选择器,所以我想只是迭代它们而不是写出10个几乎相同的代码块。

I have a class with several similar properties - UISliders, and I'd like to add actions for when a user starts and ends using each slider. Each slider will be linked to the same selector, so I was thinking of just iterating over them instead of writing out 10 nearly identical blocks of code.

问题是,最有效的方法是什么?我试过这样的事情:
在运行时遍历所有对象属性
但问题是我无法调用 addTarget:(id)目标操作:(SEL)action forControlEvents:(UIControlEvents)controlEvents on objc_property_t property 。我应该只是将属性粘贴在数组中并迭代它吗?

Question is, what's the most efficient way to do that? I tried something like this: Loop through all object properties at runtime but the problem is that I cannot call addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents on the objc_property_t property. Should I just stick the properties in an array and iterate over that?

推荐答案

如果你不需要那种活力水平涉及在运行时检查对象的属性,然后 NSArray 是最直接和可读的方式;就效率而言,我想制作一个类型为 void * 的动态数组,并且迭代可能会更快,但考虑到典型尺寸,可以在可疑的速度下获得更多的工作。

If you don't require the level of dynamism that involves inspecting the properties of your object at run time, then an NSArray is the most straightforward and readable way; as far as efficiency I guess make a dynamic array of type void * and iterate through that would be maybe faster, but more work for you at a questionable speed payoff considering typical sizes.

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

如果您确实需要调查您的房产,那么我会接近它正如另一个问题的答案所示。我的回答一开始建议将属性属性字符串解析为自定义命名属性的帐户,但显然KVC会为您处理。

If you do need to investigate your properties, then I'd approach it much as the answer on the other question suggested. My answer at first suggested parsing the property attribute string to account for custom named properties but apparently KVC takes 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);

这篇关于iOS循环对象的属性并添加操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆