我有带有通用参数化的自定义集合类。我创建了猫的集合,添加了猫。当我尝试找回 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/