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

时间:2015-10-20 16:57:02

标签: objective-c xcode generics methods return-type

我有自定义参数化的自定义集合类。我创建猫的集合,添加猫。当我试图让猫回来时Xcode显示错误:" Property' name'没有找到类型' id'"的对象。这是无稽之谈,因为Cat具有属性nameMyCustomCollection不会返回idObjectType。如何声明方法,以便自动完成可以理解方法返回哪种类型?

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

1 个答案:

答案 0 :(得分:2)

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

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

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

理论上你也可以投射customObjectAtIndex的结果,但这似乎打败了使用泛型的目的。