Objective-C class may have two special class methods:
+ (void)load;
+ (void)initialize;
Here is a simple program demonstrating this language feature:
#import <Foundation/Foundation.h>Here is the program output:
@interface First : NSObject
{
int x;
}
- (void)printX;
- (void)setX:(int)value;
@end
@implementation First
+ (void)load
{
NSLog(@"First +load");
}
+ (void)initialize
{
NSLog(@"First. +initialize");
}
- (void)printX
{
NSLog(@"First -printX");
NSLog(@"x=%i", x);
}
- (void)setX:(int)value
{
NSLog(@"First -setX");
x = value;
}
@end
@interface Second : NSObject
{
}
@end
@implementation Second
+ (void)load
{
NSLog(@"Second +load");
}
+ (void)initialize
{
NSLog(@"Second initialize");
}
@end
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSLog(@"Program starts");
First *first = [First new];
[first printX];
[first setX: 123];
[first printX];
[first release];
[pool drain];
return 0;
}
You see text "First +load" before "Program starts". It means that the class method load was called before I instantiated first object. Then, you see text "First +initialize" - the class method initialize was called when the class receives a first message. You also see text "Second +load". I do not create any object of Second class, but the method load was called anyway.
Reference:
Max OS X Reference Library. 7.1 +load: Executing code before main
No comments:
Post a Comment