Automatically call class method in objective c
my situation:
a dashboard controller who register the widgets inside it and automatically builds the view.
widget classes that are going to populate the dashboard, who adopt
<widget>
protocol(some informal methods required), and need to be registered in the dashboard class so the dashboard singleton knows who wants to be in.the dashboard class has
+(void)register:(Class<widget>)w;
that simply register the classes 开发者_如何转开发who wants to be in in an NSArray
I need each widget class to call automatically that method.in c++ i used to make a boolean static variable that i would initialize with that method. Language = objective-c
The objective-c runtime will call two methods when a class is first loaded. +load
and +initialize
. I believe what you want could be done by calling [self register]
from within +initialize
.
A way you could do it is with the runtime:
- Grab a list of all the classes known to the runtime.
- Iterate the list, and check to see if the class conforms to your widget protocol
- If it does conform to the protocol, invoke the
+register:
method or whatever
Regarding step #2, you can't use the +conformsToProtocol:
method, because one of the classes you'll iterate is the NSZombie
class, which triggers an exception whenever you invoke a method on it. Thus, you'd want to use the class_conformsToProtocol()
runtime function instead.
精彩评论