开发者

Iterate through class members in Objective-c

开发者 https://www.devze.com 2023-03-25 02:36 出处:网络
I would like to know what is the best approach in order to iterate through the members of a class in Objective-C. I want to do this so when the class changes开发者_运维知识库 I don\'t have to rewrite

I would like to know what is the best approach in order to iterate through the members of a class in Objective-C. I want to do this so when the class changes开发者_运维知识库 I don't have to rewrite a method that checks some of the class members.

I.e:

@Interface Foo : NSObject
{
    NSString *bar1;
    NSString *bar2;
}

So I want to dinamically retrieve bar1 and bar2 here.

Thank you very much!


This, given that properties and other class members can be of (radically) different types, is a Bad Idea™.

A better approach is likely to group the members you are interested together in a solitary NSDictionary or NSArray property, and iterate over that when you need to access this group of similar members.

A second approach is to have a static array of key strings in the class you are doing the checking with, containing the accessor keys for the relevant class members; and iterating over that, using the fact that @propertys are Key-Value Coding compliant, allowing you to use -valueForKey: and -setValue:forKey: in lieu of their actual accessors.

This does of course require updating the generation of that array when changing the class; so that may or may not be acceptable for your use.


This might be what you are after Objective-C Runtime Reference

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号