只是为了添加一些测试:
我创建了 2 个 MyClass 类: NSObject -> Myclass -> My2ndClass
所以:
@implementation Myclass
+(id) sharedClass {
static Myclass *miclase = nil;
miclase = [[self alloc] init];
NSLog(@"%@", [super description]);
return miclase;
}
-(id)init {
self = [super init];
NSLog(@"init de Myclass");
return self;
}
-(NSString *)description {
return @"i am Myclass";
}
@end
和:
@implementation My2ndClass
+(id) sharedClass {
static My2ndClass *miclase = nil;
miclase = [[super alloc] init];
//miclase = [super init]; CRASH
NSLog(@"%@", [super description]);
return miclase;
}
-(id)init {
self = [super init];
NSLog(@"init de My2ndClass");
NSLog(@"%@", [super description]);
return self;
}
-(NSString *)description {
return @"i am My2ndClass";
}
@end
然后在 AppDelegate 中:
Myclass *miclase = [Myclass sharedClass];
My2ndClass *mi2ndclase = [My2ndClass sharedClass];
这是控制台输出:
2012-09-03 17:18:55.742 Dynamic Typing[2891:207] init de Myclass
2012-09-03 17:18:55.744 Dynamic Typing[2891:207] Myclass
2012-09-03 17:18:55.746 Dynamic Typing[2891:207] init de Myclass
2012-09-03 17:18:55.747 Dynamic Typing[2891:207] init de My2ndClass
2012-09-03 17:18:55.748 Dynamic Typing[2891:207] i am Myclass
2012-09-03 17:18:55.751 Dynamic Typing[2891:207] My2ndClass
就像 xlc0212 所说的那样,嵌套时的正确消息是:
miclase = [super alloc];
miclase = [miclase init];
此外,如果我这样做
miclase = [super alloc]
接着
miclase = [super init]
它崩溃了。
当发送一个类方法 (+) [super description] 时,它会记录类名(Myclass 和 My2ndClass)。它们本身就是一流的,没有超级对象,是吗?