具体情况详情:
在我目前的照片应用程序中,有这样的情况:首先允许用户体验而不登录,但在从后端响应的 JSON 中没有某些字段(例如:voted、purchased 等)。如果用户登录,该字段将添加到 JSON 中。
我将展示我的实现细节如下:
PhotoListResponseModel(直接继承MTLModel)
@interface PhotoListResponseModel : MTLModel <MTLJSONSerializing>
...
@property (nonatomic, copy, readonly) NSNumber *foo;
@property (nonatomic, copy, readonly) NSArray<PhotoModel *> *subPhotos;
@end
@interface PhotoModel : MTLModel <MTLJSONSerializing>
@property (nonatomic, copy, readonly) NSNumber *photoID;
@property (nonatomic, copy, readonly) NSURL *imageUrl;
...
@end
@implementation PhotoListResponseModel
+ (NSDictionary *)JSONKeyPathsByPropertyKey {
return @{@"foo": @"foo"
@"subPhotos": @"photos"
};
}
+ (NSValueTransformer *)subPhotosJSONTransformer {
return [MTLJSONAdapter arrayTransformerWithModelClass:PhotoModel.class];
}
@end
@implementation PhotoModel
+ (NSDictionary *)JSONKeyPathsByPropertyKey {
return @{
@"photoID": @"id",
@"userID": @"user_id",
};
}
@end
相应地,JSON 示例如下:
noAuthPhoto.json
{
"foo": 1,
"photos": [
{
"id": 204748881,
"image_url": "https://foo1/bar1",
},
{
"id": 204996257,
"image_url": "https://foo2/bar2"
}
],
…
…
}
AuthedPhoto.json
{
"foo": 1,
"photos": [
{
"id": 204748881,
"image_url": "https://foo1/bar2”,
"voted": false,
"purchased": false
},
{
"id": 204996257,
"image_url": "https://foo2/bar2”,
"voted": false,
"purchased": false
}
],
...
...
}
那么,如何让新字段兼容我已经存在的代码呢?
可选属性?(我不知道该怎么做。)
或者添加继承自 PhotoListResponseModel & PhotoModel 的子类?
或任何好主意:)
更新:我注意到了这个信息,但仍然不知道该怎么做。