2015-10-20 27 views
2

我有具有泛型参数化的自定义集合类。我创建猫的集合,添加猫。当我试图让猫回来时,Xcode显示错误:“在'id''类型的对象上找不到'属性'名称'”。这是无稽之谈,因为Cat有财产nameMyCustomCollection不返回idObjectType。我该如何声明方法,以便自动完成可以理解该方法返回哪种类型?具有泛型和Xcode自动完成功能的Objective-C方法返回类型

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 

回答

2

的问题是不是与方法声明。它是collection变量的声明。你必须告诉编译器是什么类型的对象都在收集:

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

要不然也不会知道collection变量引用什么样的对象,并假定它们是id类型(因此误差)。

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