0

If I have a class thus:

@interface Fields : NSObject {
@public
NSString* location;
NSString* keywords;
}
@end

Can I access not only the values of location & keywords but also the names of these variables? i.e. "location" and "keywords" ? These names will be passed between computers and are not displayed to users.

Or... do I use a dictionary and keep code and data separate?

Carl
  • 2,896
  • 2
  • 32
  • 50
  • 1
    I think it's different in that there is a difference between properties and instance variables. Closely related though! – Carl Jan 17 '14 at 18:27
  • 1
    @Carl While you can do so, I'd recommend against it. This kind of meta-programming is really a bit alien to the design patterns of ObjC and going down this kind of a route will generally end in painful debugging and maintenance issues. – bbum Jan 17 '14 at 23:22
  • thanks @bbum. I agree with you that, while this kind of access is fully supported in some languages, we're off the beaten Obj C path. I am going to use a different approach and duplicate the variable names in data instead. I'll leave Aaron Brager's answer marked as accepted for those wanting such a solution. – Carl Jan 20 '14 at 09:37

1 Answers1

1

You can get a list of ivars for a class using class_copyIvarList.

For example:

unsigned int count = 0;
Ivar* ivars = class_copyIvarList([self class], &count);
for(int i = 0; i < count; ++i) {
    NSLog(@"%@::%s", NSStringFromClass([self class]), ivar_getName(ivars[i]));
}
free(ivars);
Aaron Brager
  • 65,323
  • 19
  • 161
  • 287