我有自定义参数化的自定义集合类。我创建猫的集合,添加猫。当我试图让猫回来时Xcode显示错误:" Property' name'没有找到类型' 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
答案 0 :(得分:2)
问题不在于方法声明。它是collection
变量的声明。您必须告诉编译器集合中的对象类型:
MyCustomCollection<Cat *> *collection = [[MyCustomCollection<Cat *> alloc] init];
否则它将不知道collection
变量引用的对象类型,并假设它们是id
类型(因此错误)。
理论上你也可以投射customObjectAtIndex
的结果,但这似乎打败了使用泛型的目的。