我有一个简单的类层次结构,其构造函数使用instancetype
而不是id
作为返回类型。如果我想转发给超类的构造函数,我得到这样的警告:使用实例类型与ID的类层次结构
返回车辆*从方法*返回车:接口车辆没有车
如果我切换的继任者从instancetype
到id
,当然,由于类型严格性较低,错误消失。推荐的方法是什么?
Vehicle.h
@interface Vehicle
- (instancetype)initWithIdentifier:(NSString *)anIdentifier
@end
Vehicle.m
@implementation Vehicle
- (instancetype)initWithIdentifier:(NSString *)anIdentifier {
self = [super init];
if (self) {
// do a bunch of stuff to construct the object
}
return self;
}
@end
Car.h
@interface Car : Vehicle
- (instancetype)initWithCarID:(NSString *)aCarId
@end
Car.m
@implementation Car
- (instancetype)initWithCarID:(NSString *)aCarId {
// I want to forward the call to the parent and preserve the
// two different constructor signatures
// The following line produces this warning:
// Returning Vehicle * from a method returning Car *: interface Vehicle is not a successor of Car
return [super initWithVehicleIdentifier:aCarId];
}
@end
因此instancetype只对类构造函数是必需的吗? –
隐含相关结果类型的方法是'alloc','+ new','-init','-retain','-autorelease'和'-self',@Will。更多细节[在Clang文档中](http://clang.llvm.org/docs/LanguageExtensions.html#related-result-types)。 –
@我会更新我的答案。 –