Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

safe __attribute__((constructor)) function classes

Is it safe to use classes defined in you own project within __attribute__((constructor)) functions? Has the objective-C runtime had a chance to do what it needs to do with your classes when __attribute__((constructor)) functions are called? Or am I misunderstanding how the runtime loads classes and there is no difference between library class and your own in this context?

like image 428
Nathan Day Avatar asked Jan 23 '12 21:01

Nathan Day


1 Answers

I'll suggest you use + initialize or + load rather than the attribute, but that is my preference.

The + load method of a class is called when the class is loaded by the runtime.

The + initialize method of a class is called before any other method in the class.

From the docs for load:

On Mac OS X v10.5, the order of initialization is as follows:

  1. All initializers in any framework you link to.
  2. All +load methods in your image.
  3. All C++ static initializers and C/C++ attribute(constructor) functions in your image.
  4. All initializers in frameworks that link to you.

In addition:

  • A class’s +load method is called after all of its superclasses' +load methods.
  • A category +load method is called after the class's own +load method.

In a +load method, you can therefore safely message other unrelated classes from the same image, but any +load methods on those classes may not have run yet.

Which makes it clear any attributed or + load methods will run after the runtime is initialized. And as + load is a method on your class and is run before any attributed methods then before either the runtime must have set up your class.

like image 63
CRD Avatar answered Nov 15 '22 08:11

CRD