1

我只是想了解客观的 C 对象运行时过程

从 Object Refs 中,对象的 +Initialize 方法将在它第一次调用某个方法时被调用。我运行如下测试文件。我想知道为什么这些对象只调用了 +load 。


// InitializeTest.h
@interface InitializeTest : NSObject {
@private
}
- (void) show;
@end


@interface InitializeTest(Category)
+ (void) load;
+ (void) initialize;
@end


@interface InitializeTestSub : InitializeTest {
@private
}
- (void) showSub;
@end

@interface InitializeTestSub(Category)
+ (void) load;
+ (void) initialize;
@end


//InitializeTest.m
#import "InitializeTest.h"

@implementation InitializeTest
+ (void) load {
    NSLog(@"%s %@",__func__,self);
}

+ (void) initialize {
    NSLog(@"%s %@",__func__,self);
}

- (void) show {
    NSLog(@"%s",__func__);
}
@end


@implementation InitializeTest(Category)
+ (void) load {
    NSLog(@"Category %s %@",__func__,self);
}

+ (void) initialize {
    NSLog(@"Category %s %@",__func__,self);
}
@end


@implementation InitializeTestSub
+ (void) load {
    NSLog(@"%s %@",__func__,self);
}

+ (void) initialize {
    NSLog(@"%s %@",__func__,self);
}

- (void) showSub {
    NSLog(@"%s",__func__);
}
@end

@implementation InitializeTestSub(Category)
+ (void) load {
    NSLog(@"Category %s %@",__func__,self);
}

+ (void) initialize {
    NSLog(@"Category %s %@",__func__,self);
}
@end

//test Code
    InitializeTest* test = [[InitializeTest alloc] init];
    InitializeTestSub *testSub = [[InitializeTestSub alloc] init];

    [test class];
    [testSub class];


    [test show];
    [testSub show];
    [testSub showSub];

//////////////////////////////////////////////////
//Result
+[InitializeTest load] InitializeTest
+[InitializeTestSub load] InitializeTestSub
Category +[InitializeTest(Category) load] InitializeTest
Category +[InitializeTestSub(Category) load] InitializeTestSub
-[InitializeTest show]
-[InitializeTest show]
-[InitializeTestSub showSub]
4

1 回答 1

2

+initialize不打算被类别使用,只有类本身。运行时可能会看到两种不同的+initialize方法,因此也没有运行。请参阅NSObject 的类参考中的+initialize (特殊注意事项部分)。

于 2011-04-08T01:27:09.073 回答