This document is meant to describe some of the GNU Objective-C runtime features. It is not intended
to teach you Objective-C, there are several resources on the Internet that present the language. Ques-
tions and comments about this document to Ovidiu Predescu mailto:ovidiu@@cup.hp.com.
8.1.
: Executing code before main
+load
The GNU Objective-C runtime provides a way that allows you to execute code before the execution
of the program enters the
through a special class method
This facility is very useful if you want to initialize global variables which can be accessed by the
program directly, without sending a message to the class first. The usual way to initialize global
variables, in the
+initialize
when the first message is sent to a class object, which in some cases could be too late.
Suppose for example you have a
global variables, like below:
FileStream *Stdin = nil;
FileStream *Stdout = nil;
FileStream *Stderr = nil;
@implementation FileStream
+ (void)initialize
{
Stdin = [[FileStream new] initWithFd:0];
Stdout = [[FileStream new] initWithFd:1];
Stderr = [[FileStream new] initWithFd:2];
}
/* Other methods here */
@end
In this example, the initialization of
The programmer can send a message to one of these objects before the variables are actually initial-
ized, thus sending messages to the
the global variables is not invoked until the first message is sent to the class object. The solution would
require these variables to be initialized just before entering
The correct solution of the above problem is to use the
@implementation FileStream
+ (void)load
{
Stdin = [[FileStream new] initWithFd:0];
Stdout = [[FileStream new] initWithFd:1];
Stderr = [[FileStream new] initWithFd:2];
}
/* Other methods here */
@end
GNU Objective-C runtime features
function. The code is executed on a per-class and a per-category basis,
main
.
+load
method, might not be useful because
FileStream
,
Stdin
object. The
nil
class that declares
and
Stdout
Stderr
+initialize
.
main
method instead of
+load
Chapter 8.
+initialize
,
and
Stdin
Stdout
in
occurs too late.
+initialize
method which actually initializes
+initialize
is only called
as
Stderr
:
Need help?
Do you have a question about the ENTERPRISE LINUX 3 - USING GCC and is the answer not in the manual?
Questions and answers