Question

Is there a standard mechanism with Objective C and the iOS runtime to register setup code?

Why?

The advantage of this is that you can decouple your code nicely.

  • If a subsystem needs particular setup, the set up stays in that subsystem.

  • If a group of files need to register that they should all be offered as a particular service, that can be encapsulated in individual files that offer the service and there is no need for a separate configuration file to be kept up to date.

Getting the code to run isn't especially important – I can do that myself with various entry points. What I need is for the compiler or linker or run time or magic to be able to collect up anything that I've registered in different parts of a program, and let me have it when I need it.

How to in c++

With c++, I've typically arranged for this with static instances that are constructed before main() is called. I could use objective-c++, but I'd much prefer to use a standard mechanism.

Thanks.

Was it helpful?

Solution 2

Registering Code

Use the class method +(void) load for components that need to self register themselves.

Note that the load method is run on all subclasses and all categories. This is nothing like the the normal method calling behaviour.

Creating a Registry

If components need to register themselves in some kind of container, use the class method +(void) initialise to create a container to hold the components that are going to register themselves. It seems from my limited testing that initialize can be called before load when a load method uses a class with an initialize method, which is pretty cool if reliable.

Running Registered Code

If the components should do something at some specific entry point of your App, then at that entry point, grab the registered components from the registry and do that thing. Eg, you might extend you UIApplicationDelegate's -(BOOL) application:didFinishLaunchingWithOptions: to actually perform the setup stages the components registered.

In my case, I actually want the registered code to get run every time a specific kind of object is constructed, so I call the registered methods there and let them have the object being constructed.

More references on load and initialise

Thank you for the answers and comments that let me put this answer together.

OTHER TIPS

I would look up:

+ (void)initialize

This method is called whenever a message is first sent to the class meta-object, such as, for example, when alloc-ing an object of that class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top