iOS:方法返回类型应该是类X的子类

时间:2012-08-07 08:06:25

标签: ios generics subclass

我有一个名为“BaseEntry”的类和一些特定的类,如“EntryFoo”和“EntryBar”,它们是“Base Entry”的子类。

现在有一个函数getEntry,它应该返回一个Object,它是BaseEntry的子类。在Java中,这不是问题,但我不知道如何在Objective-C for iOS中解决这个问题。

感谢您的帮助! 亚历

2 个答案:

答案 0 :(得分:3)

在Objective-C中执行此操作的标准方法是返回类型为“id”的对象;在Java中将其视为Object。但是,id稍微好一点,因为您可以将返回值分配给没有强制转换的类型值。

澄清一下,您的选择是:

// Assuming -(BaseEntry*)getEntry;
id entry = [obj getEntry];
[entry messageOnlyOnFooEntry];

// Assuming -(BaseEntry*)getEntry; - note cast required
FooEntry *entry = (FooEntry*)[obj getEntry];
[entry messageOnlyOnFooEntry];

// Assuming -(id)getEntry; - no cast required
FooEntry *entry = [obj getEntry];
[entry messageOnlyOnFooEntry];

答案 1 :(得分:0)

BaseEntry gE = [[BaseEntry alloc] init]; // Allocate and init a BaseEntry object
returnGetEntryHere = [ge getEntry]; // This will execute getEntry which is a method in BaseEntry

你到现在为止做过什么尝试吗?如果您发布一些代码,也许人们会帮助您解决有关您的objective-c项目的误解和缺点

相关问题