开发者

iPhone OS: Get a list of methods and variables from anonymous object

I am building my first iPhone/Obj-c app and I have a large amount of data-holding subclasses that I am passing into a cite function. To the cite function these objects are anonymous and I need to find a way to access all the variables of each passed object. I have been using a pre-built NSArray and Selectors to do this but with more than 30 entries (and growing) it is kind of silly to do manually. There has to be a way to dynamically look up all the variables of an anonymous object.

The obj-c runtime run-time docs mention this problem but from what I can tell this is not available in iPhone OS. If it is then I don't understand the implementation and need some guidance. A similar question was asked before but again I think they we开发者_JS百科re talking about OSX and not iPhone.

Any thoughts?

-(NSString*)cite:(id)source {
 NSString *sourceClass = NSStringFromClass([source class]);

 // Runs through all the variables in the manually built methodList
 for(id method in methodList) {
  SEL x = NSSelectorFromString(method);
  // further implementation

 // Should be something like
 NSArray *methodList = [[NSArray alloc] initWithObjects:[source getVariableList]]
 for(id method in methodList) {
  SEL x = NSSelectorFromString(method);
  // Further implementation
 }


The runtime is the same on the Mac as it is on the iPhone. If the other question does what you're looking for, then it should work. If it doesn't, file a bug.

In the meantime, given a Class, you can retrieve a list of all of its selectors using the class_copyMethodList() function:

unsigned int numMethods = 0;
Method * methods = class_copyMethodList(sourceClass, &numMethods);
NSMutableArray * selectors = [NSMutableArray array];
for (int i = 0; i < numMethods; ++i) {
  SEL selector = method_getName(methods[i]);
  [selectors addObject:NSStringFromSelector(selector)];
}
free(methods);


It's certainly possible to do this through the Objective-C runtime functions, but it's probably not the right way to go about it. Since you're creating the objects passed into the cite method, just have them each implement a protocol that cite can use to extract whatever information it needs.

Something like the Key-Value Coding protocol will probably do what you want: http://developer.apple.com/iphone/library/documentation/cocoa/Conceptual/KeyValueCoding/KeyValueCoding.html

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜