-1
如何處理JSONModel中的子類化集合屬性?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相同的繼承屬性,但它需要subclassed類型的orders數組。 然而,這會導致編譯器警告:
Property type 'NSArray<OrderDetailModel> *' is incompatible with type
'NSArray<OrderListModel> *' inherited from 'ProductListModel'
我發現這個相關SO post但我寧願不猴子修補JSONModel庫。
編輯#1:
這在#574進行了討論,在此之前#229 github上的問題,但需要一個「類型」字符串來確定實例化哪個類。這需要對後端API進行更改。
有沒有辦法做到這一點,而無需更改後端API?
不能重寫屬性在子類中有不同的類型,因爲這將違反里氏替換原則。 – Paulw11
當然,你是完全正確的..我將不得不介紹ProductListModel和ProductDetailModel繼承自的ProductBaseModel。謝謝@ Paulw11 – Andy