我注意到今天在玩“init”时,下面的两个对象都会向控制台输出相同的消息“_init:TireSnow”。任何人都可以解释为什么会发生这种情况吗?
// INTERFACE
@interface TireBasic : NSObject {
}
@end
@interface TireSnow : TireBasic {
}
@end
// IMPLEMENT
@implementation TireBasic
- (id) init {
self = [super init];
if(self) {
NSLog(@"TB_init: %@", NSStringFromClass([self class]));
}
return self;
}
- (NSString *) description {
return @"This is a BASIC TIRE.";
}
@end
@implementation TireSnow
- (id) init {
self = [super init];
if(self) {
NSLog(@"TS_init: %@", NSStringFromClass([self class]));
}
return self;
}
- (NSString *) description {
return @"This is a SNOW TIRE.";
}
@end
#import <Foundation/Foundation.h>
#import "CarParts.h"
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int tireCount;
CarClass *newCar_001;
EngineClass *newEngine_001;
TireBasic *newTire_BASIC;
TireSnow *newTire_SNOW;
// Setup
NSLog(@"COMPOSITION Start");
newCar_001 = [[CarClass alloc] init];
// Engine
newEngine_001 = [[EngineClass alloc] init];
[newCar_001 setEngine: newEngine_001];
// TIRES (BASIC)
for(tireCount=0; tireCount<2; tireCount++) {
newTire_BASIC = [[TireBasic alloc] init];
[newCar_001 setTire:newTire_BASIC];
[newTire_BASIC release];
}
// TIRES (SNOW)
for(tireCount=0; tireCount<2; tireCount++) {
newTire_SNOW = [[TireSnow alloc] init];
[newCar_001 setTire:newTire_SNOW];
[newTire_SNOW release];
}
// Display
[newCar_001 printCar];
// Clean up
[newCar_001 release];
[newEngine_001 release];
[pool drain];
return 0;
}
> COMPOSITION Start
> _init: CarClass
> _init: EngineClass
> TB_init: TireBasic
> TB_init: TireBasic
> TB_init: TireSnow *****
> TS_init: TireSnow
> TB_init: TireSnow *****
> TS_init: TireSnow
>
> This is a BASIC TIRE.
> This is a BASIC TIRE.
> This is a SNOW TIRE.
> This is a SNOW TIRE.
>
> _deal: CarClass
> TB_deal: TireBasic
> TB_deal: TireBasic
> TS_deal: TireSnow
> TB_deal: TireSnow ******
> TS_deal: TireSnow
> TB_deal: TireSnow ******
> _deal: EngineClass
带有星星的线来自TireSnow [super init]和[super dealloc],似乎每次都返回“TireSnow”的[自我类],有人可以解释为什么吗?
非常感谢加里
答案 0 :(得分:3)
> TS_deal: TireSnow
> TB_deal: TireSnow
你问为什么 TireSnow 打印两次?
先运行[TireBasic init]
,然后[TireSnow init]
。在这两种情况下,他们都会打印类名,在这两种情况下,类名都是TireSnow
。
换句话说,[self class]
将始终返回相同的对象,无论它在哪个方法中执行。
答案 1 :(得分:1)
TireSnow将在TireBasic init中将其类记录两次,一次在TireSnow init中,一次从super调用到。
只是为了检查:你是否可能会混淆来自TireSnow的两个日志来自TireBasic和TireSnow?
答案 2 :(得分:0)
我们能看到你的[[_____ alloc] init]声明吗?我看不出怎么样
[[TireSnow alloc] init]和[[TireBasic alloc] init]将返回相同的内容。好吧,也许如果:
TireSnow *tire;
tire = (TireSnow *) [TireBasic alloc];
tire = [tire init];