Specific situation detail:
In my current photo app, There are such situation : allow user experience first without log in, but no have some field(e.g:voted,purchased ,etc) in the JSON responded from backend. If user logged in, the field is added in JSON .
I'll show off my implement details as following:
PhotoListResponseModel (directly inherit 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
Correspondly, the JSON example as following:
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
}
],
...
...
}
So, how let new field can compatible my already existing code?
Optional Property? (I not know how to do this.)
Or add a subclass of inherit from PhotoListResponseModel & PhotoModel?
Or any good idea : )
Update: I noticed this information,but still don't know how to do it.