Wie gehen Sie mit Subclassing-Auflistungsattributen in JSONModel um?Best Practices für JSONModel und Polymorphismus
Nehmen wir an, ich habe diese beiden Endpunkte mit unterschiedlichen Antworten des gleichen "Produktobjekts".
domain.com/api/1.0/getProductList
domain.com/api/1.0/getProductDetails/productId
schrieb ich einige Beispiel-Code unten Sie mein Problem zeigen:
// 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
Das ProductDetailModel möchte dieselben vererbten Attribute wie ProductListModel, möchte aber das Array orders im Unterklasse-Typ. Jedoch führt dies zu einem Compiler-Warnung:
Property type 'NSArray<OrderDetailModel> *' is incompatible with type
'NSArray<OrderListModel> *' inherited from 'ProductListModel'
fand ich diesen verwandten SO post aber ich möchte lieber Affe nicht die JSONModel Bibliothek patchen.
Edit # 1:
Das hat zuvor in der #574 und #229 Github Fragen diskutiert worden, aber erfordert einen "Typ" string, um zu bestimmen, welche Klasse zu instanziiert. Dies erfordert eine Änderung der Back-End-API.
Gibt es eine Möglichkeit, dies zu tun, ohne die Back-End-API zu ändern?
Sie können die Eigenschaft in der Unterklasse nicht mit einem anderen Typ überschreiben, da dies gegen das Liskov-Substitutionsprinzip verstößt. – Paulw11
Natürlich haben Sie völlig Recht .. Ich muss ein ProductBaseModel einführen, von dem ProductListModel und ProductDetailModel erbt. Danke @ Paulw11 – Andy