如果我正确理解您的问题,我相信关键是 [self class] 成语。
就您的更新请求一种在当前类上调用类方法的方法而言,您可以使用[self class]
. 如:
Structure *newStructure = [[self class] fetchStructureByID:[currentDictionary
objectForKey:@"myId"]];
inContext:managedObjectContext];
编辑:我重新做了这个以id
根据@rpetrich 的评论返回——-isKindOfClass:
只要你确定你正在调用的实例的类型,它就更干净了,并且避免了这种需要-createConfiguredObject
。
至于第一部分,您可以只返回一个id
(指向任何对象的指针)并记录它将返回它所调用的同一类的实例。然后在代码中,您需要在方法中实例化新对象的任何地方使用 [self class]。
例如,如果您有一个-createConfiguredObject
方法返回调用它的同一个类的实例,那么它将按如下方式实现:
// 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";
作为参考,我所指的-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
}