我有以下的情況,我不能解析:的Objective-C,階級身份
@interface Deck : NSObject
@interface MasterDeck : Deck
@interface PlayerDeck : Deck
裏面MasterDeck
類,在初始化過程中,我呼籲在
[self cutDeckImageIntoCards]; // We don't get to execute this method
通話效果error [PlayerDeck cutDeckImageIntoCards]: unrecognized selector sent to instance
確實,PlayerDeck
沒有這個方法..但是爲什麼它被調用呢?
看着MasterDeck的初始化後,我增加了一些調試語句:
static MasterDeck *gInstance = NULL;
+(MasterDeck *) instance {
@synchronized(self) {
if (gInstance == NULL) {
gInstance = [[self alloc] init];
}
}
return gInstance;
}
-(id) init {
if (gInstance != NULL) {
return gInstance;
}
// MasterDeck
self = [super init];
// PlayerDeck
if (self) {
// Lots of stuff
[self cutDeckImageIntoCards]
// Some more stuff
}
gInstance = self;
return gInstance;
}
好了,MasterDeck是PlayerDeck因爲」甲板認爲它是一個PlayerDeck ......甲板證實
甲板是創建如下:
static Deck *gInstance = NULL;
+(Deck *) instance {
@synchronized(self) {
if (gInstance == NULL) {
gInstance = [[self alloc] init];
}
}
return gInstance;
}
-(id) init {
if (gInstance != NULL) {
return gInstance;
}
self = [super init];
if (self) {
// Do something
}
NSLog(@"Deck thinks it's a %@", [[self class ]description]); // PlayerDeck
gInstance = self;
return gInstance;
}
所以,再次
@interface Deck : NSObject
假設上述辛格爾頓執行,爲什麼會甲板認爲它實際上是一個PlayerDeck?
顯示創建此對象的代碼,'self'。您必須無意中創建了PlayerDeck實例 –
如果將MasterDeck直接更改爲子類NSObject並獨立實現super的init方法,會發生什麼情況?如果問題消失,那可能會給你一個線索。也許Deck的init方法錯誤地實例化PlayerDeck。 – Wienke
@Wienke,我想到了,似乎並不是這樣..我在這裏也發佈了Deck的初始化代碼 – JAM