如何处理JSONModel中的子类化集合属性?
假设我有两个端点,它们对同一个“产品对象”的响应不同。
domain.com/api/1.0/getProductList
domain.com/api/1.0/getProductDetails/productId
我在下面写了一些示例代码来向您展示我的问题:
// ProductListModel
@interface ProductListModel : JSONModel
@property (nonatomic, strong) NSNumber *productId;
@property (nonatomic, strong) NSNumber *userId;
@property (nonatomic, strong) NSArray<OrderListModel> *orders;
@end
// ProductDetailModel
@interface ProductDetailModel : ProductListModel
@property (nonatomic, strong) NSURL *productImageUrl;
@property (nonatomic, strong) NSArray<OrderDetailModel> *orders;
@end
// OrderListModel
@protocol OrderListModel <NSObject>
@end
@interface OrderListModel : JSONModel
@property (nonatomic, strong) NSNumber *orderId;
@property (nonatomic, strong) NSNumber *price;
@end
// OrderDetailModel
@protocol OrderDetailModel <NSObject>
@end
@interface OrderDetailModel : OrderListModel
@property (nonatomic, strong) NSURL *orderImageUrl;
@end
ProductDetailModel需要与ProductListModel相同的继承属性,但它需要子类型中的orders数组。 但是这会导致编译器警告:
Property type 'NSArray<OrderDetailModel> *' is incompatible with type
'NSArray<OrderListModel> *' inherited from 'ProductListModel'
我发现这与SO post有关,但我宁愿不修补JSONModel库。
编辑#1:
之前在#574和#229 github问题中已经讨论过这个问题,但是需要一个“type”字符串来确定要实例化的类。这需要对后端API进行更改。
有没有办法在不更改后端API的情况下执行此操作?
答案 0 :(得分:0)
您不能覆盖子类中的属性以使其具有不同的类型,因为它会违反Liskov替换原则 - @ Paulw11
对于未来的读者,这里是更新的示例代码的样子:
// ProductBaseModel
@interface ProductBaseModel : JSONModel
@property (nonatomic, strong) NSNumber *productId;
@property (nonatomic, strong) NSNumber *userId;
@end
// ProductListModel
@interface ProductListModel : ProductBaseModel
@property (nonatomic, strong) NSArray<OrderListModel> *orders;
@end
// ProductDetailModel
@interface ProductDetailModel : ProductBaseModel
@property (nonatomic, strong) NSURL *productImageUrl;
@property (nonatomic, strong) NSArray<OrderDetailModel> *orders;
@end
// OrderListModel
@protocol OrderListModel <NSObject>
@end
@interface OrderListModel : JSONModel
@property (nonatomic, strong) NSNumber *orderId;
@property (nonatomic, strong) NSNumber *price;
@end
// OrderDetailModel
@protocol OrderDetailModel <NSObject>
@end
@interface OrderDetailModel : OrderListModel
@property (nonatomic, strong) NSURL *orderImageUrl;
@end