我有一個簡單的類層次結構,其構造函數使用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)。 –
@我會更新我的答案。 –