如果我正确理解您的问题,我相信关键是 [self class] 习语。
就您的更新请求调用当前类的类方法而言,您可以使用[self class]。如:
Structure *newStructure = [[self class] fetchStructureByID:[currentDictionary
objectForKey:@"myId"]];
inContext:managedObjectContext];
编辑:我重做这个以根据@rpetrich 的评论返回id——只要你确定你正在调用-createConfiguredObject 的实例类型,就更干净,并且避免需要-isKindOfClass: .
至于第一部分,您可以只返回一个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
}