将方法发送到所有属性(响应它)

时间:2014-06-23 10:59:50

标签: ios dynamic properties

假设您有一个具有各种属性的类

@interface Tank : UIViewController

@property (strong) Part *part;
@property (strong) Wheel *wheel;
@property (strong) Radar *radar;

@property (strong) IBOutlet UIView *blah;
@property (strong) IBOutlet UILabel *blah;
@property (strong) IBOutlet UIView *blah;

@end

在示例中,Part,Wheel,Radar的所有部分都是UIExcitingView

UIExcitingView回复specialSetup

请注意,显然在特定的类中,我可以使用数组,例如,将specialSetup发送到每个项目。

但是,我想将UIViewController子类化为UISuperViewController,

这样每次都会自动进行此操作。

简单地说,在设置时,UISuperViewController应该这样做......

for each property in the class
if it responds to specialSetup
send specialSetup to it

交替,

for each property in the class
if it is of class UIExcitingView
send specialSetup to it

那么,你如何迭代所有属性,并检查它是否是UIExcitingView

1 个答案:

答案 0 :(得分:3)

使用此方法并遍历所有属性并检查它们是否响应您想要的方法。

objc_property_t *properties = class_copyPropertyList([self class], &outCount);

使用此选项获取属性名称

objc_property_t property = properties[i];
 const char *propName = property_getName(property);

用它来检查它是否响应了你的方法。

[[self valueForKey:[NSString stringWithUTF8String:propName]] respondsToSelector:@selector(methodName)];

如果属性响应,请使用此命令发送消息。

[[self valueForKey:[NSString stringWithUTF8String:propName]]  performSelector:@selector(methodName)];