如果我正確理解你的問題,我相信關鍵是[self class]成語。
只要您的更新要求調用當前類的類方法,您可以使用[self class]
。如:
Structure *newStructure = [[self class] fetchStructureByID:[currentDictionary
objectForKey:@"myId"]];
inContext:managedObjectContext];
編輯:我重做這每@ rpetrich的評論返回id
- 更清潔,只要你確定你調用-createConfiguredObject
實例的類型,避免了-isKindOfClass:
的需要上。對於第一部分,您可以返回一個id
(指向任何對象的指針)並記錄它將返回它所調用的同一類的實例。然後在代碼中,您需要在實例化方法中的新對象的任何地方使用[self class]。
例如
// Returns an instance of the same class as the instance it was called on.
// This is true even if the method was declared in a base class.
-(id) createConfiguredObject {
Structure *newObject = [[[self class] alloc] init];
// When this method is called on a subclass newObject is actually
// an instance of that subclass
// Configure newObject
return newObject;
}
然後,您可以在代碼中使用此如下:
StructureSubclass *subclass = [[[StructureSubclass alloc] init] autorelease];
subclass.name = @"subclass";
// No need to cast or use isKindOfClass: here because returned object is of type id
// and documented to return instance of the same type.
StructureSubclass *configuredSubclass = [[subclass createConfiguredObject] autorelease];
configuredSubclass.name = @"configuredSubclass";
因爲如果你有一個-createConfiguredObject
方法,它返回它被稱爲在同一類的一個實例,它將實現如下參考,我指的-isKindOfClass:
和鑄造到適當的子類如下:
Structure *structure;
// Do stuff
// I believe structure is now pointing to an object of type StructureSubclass
// and I want to call a method only present on StructureSubclass.
if ([structure isKindOfClass:[StrucutreSubclass class]]) {
// It is indeed of type StructureSubclass (or a subclass of same)
// so cast the pointer to StructureSubclass *
StructureSubclass *subclass = (StructureSubclass *)structure;
// the name property is only available on StructureSubclass.
subclass.name = @"myname";
} else {
NSLog(@"structure was not an instance of StructureSubclass when it was expected it would be.");
// Handle error
}
構造函數/初始化方法通常返回'id'出於這個原因。 – rpetrich 2010-06-09 00:05:41