Objective-C的子类和基类铸造

问题描述:

我将创建一个基类,为所有子类实现非常类似的功能。这是在different question中回答的。但是我现在需要知道的是如果/如何可以投入各种函数(在基类中)来返回子类对象。这既适用于给定的函数,也适用于函数调用。Objective-C的子类和基类铸造

(我的方式与CoreData工作)

基类中的功能(这是与将要成为我的子类)

+(Structure *)fetchStructureByID:(NSNumber *)structureID inContext:(NSManagedObjectContext *)managedObjectContext {...} 

而作为一个给定函数中的函数调用:

Structure *newStructure = [Structure fetchStructureByID:[currentDictionary objectForKey:@"myId"]]; 
               inContext:managedObjectContext]; 

结构是我的一个子类,所以我需要重写这两种使他们“通用”,并可以应用到其他的亚型(谁正在调用该函数)。

我该怎么做?

更新:我刚刚意识到,在第二部分实际上有两个问题。您不能将[Structure fetch ...]更改为[self fetch ...],因为它是类方法,而不是实例方法。我该如何解决这个问题?

+1

构造函数/初始化方法通常返回'id'出于这个原因。 – rpetrich 2010-06-09 00:05:41

如果我正确理解你的问题,我相信关键是[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 
} 
+0

“在投射到适当的子类之前”是什么意思? 到目前为止,这对我有很大帮助,但我仍试图解决一些问题。特别是当试图设置一个变量像newObject.name = ...因为结构(在你的情况下基类)没有名称,但子类。在那种情况下,我是否需要让Structure看起来像它也有这些变量? – RyanJM 2010-06-08 21:35:44

+0

对不起,迟到的回应。我花了一段时间来实现它。这真的很有帮助,谢谢。 – RyanJM 2010-06-23 22:32:34

+0

不客气。我很高兴这很有帮助。 – 2010-06-23 23:42:12