具有泛型和 Xcode 自动完成功能的 Objective-C 方法返回类型

标签 objective-c xcode generics methods return-type

我有带有通用参数化的自定义集合类。我创建了猫的集合,添加了猫。当我尝试找回 cat 时,Xcode 显示错误:“在‘id’类型的对象上找不到属性‘名称’”。这是无稽之谈,因为 Cat 具有属性 name 并且 MyCustomCollection 不返回 id 而是 ObjectType。如何声明方法,以便自动完成功能可以了解该方法返回哪种类型?

MyCustomCollection *collection = [[MyCustomCollection<Cat *> alloc] init];
[collection addCustomObject:[[Cat alloc] init]];
NSString *string = [collection customObjectAtIndex:0].name; // Property 'name' not found on object of type 'id'

MyCustomCollection.h 文件

@interface MyCustomCollection<ObjectType> : NSObject
-(ObjectType)customObjectAtIndex:(NSUInteger)index;
-(void)addCustomObject:(ObjectType)object;
@end

Cat.h文件

@interface Cat : NSObject
@property (nonatomic, strong) NSString *name;
@end

最佳答案

问题不在于方法声明。它是集合变量的声明。您必须告诉编译器集合中的对象是什么类型:

MyCustomCollection<Cat *> *collection = [[MyCustomCollection<Cat *> alloc] init];

否则它不会知道 collection 变量引用的对象类型,并假定它们是 id 类型(因此会出现错误)。

理论上您也可以转换 customObjectAtIndex 的结果,但这似乎违背了使用泛型的目的。

关于具有泛型和 Xcode 自动完成功能的 Objective-C 方法返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33242472/

相关文章:

java - 另一个对泛型感到困惑的可怜灵魂...如何向此代码添加静态 .start() 方法?

iphone - 使用自定义 View 或 UIImageView

objective-c - 错误 : Argument list too long: recursive header expansion failed at/Applications/iWork '09/Pages. 应用程序/.../内容/资源

objective-c - typedef 枚举到 Swift 枚举。如何使用案例来标记idleTimerDisabled检测的Pause和Resume?

objective-c - 如何使用 Facebook SDK 3.2 向 FBWebDialogs 添加图片

swift - 如何创建一个函数来返回两个不同数组中的值的匹配项?

iOS:JSONObjectWithData

xcode - 如何告诉 Xcode 在进程启动后立即将调试器附加到进程?

c# - 约束参数,new()

java - 有没有办法使用Java泛型类型来编写排序算法?