Why is there no way to do introspection in Objective C with Objects?
I have seen examples (on here especially) of calling hideous C functions and getting structures back that have to be iterated, replete with reams o开发者_StackOverflowf underbars.
Why can't I do this (pseudo to follow):
Money *cost = [[Money alloc] init];
for (Property *property in [[cost class] properties]){
..
}
for (Method *method in [[cost class] methods]){
..
}
?
Those functions are not hideous. They are all documented in the Objective-C Runtime Reference.
One reason I think there aren't the +properties
and +methods
methods are because it's rare you need to look for property/method that you don't know the name in compile time.
The most useful introspection functions in ObjC are -respondsToSelector:
, -isKindOfClass:
, -conformsToProtocol:
, NSInvocation
, KVC, KVO, NSXxxxFromString, and they are operating with objects.
Here's why you can't do it: Because Cocoa operates on a level above the runtime. The Objective-C runtime functions can't reasonably depend on Cocoa, an optional library implemented on top of it. It would be possible to create an object-oriented layer on top of the runtime API, but this was not a design goal of Cocoa. It's just not necessary to do what Cocoa does.
Check out NSClassDescription and the cover methods on NSObject. This may be close to what you are looking for.
精彩评论