1

具体情况详情:

在我目前的照片应用程序中,有这样的情况:首先允许用户体验而不登录,但在从后端响应的 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 的子类?

或任何好主意:)


更新:我注意到了这个信息,但仍然不知道该怎么做。

4

1 回答 1

0

可选属性仅在 Swift 中可用,但对于 Obj-C 的类似想法——具有可能nil值的对象——应该可以很好地工作。您可以将以下NSNumber属性添加到您的PhotoModel:

@property (nonatomic, strong) NSNumber *voted;
@property (nonatomic, strong) NSNumber *purchased;

PhotoModel并在对象创建过程中从解析的 JSON 中分配您的 BOOL 值,如下所示:

photoModelObject.voted = [NSNumber numberWithBool:[parsedJson valueForKey:@"voted"]];
photoModelObject.purchased = [NSNumber numberWithBool:[parsedJson valueForKey:@"purchased"]];

接下来,当您引用您的照片对象时,只需检查这些属性是否nil有价值。如果他们是 - 您的用户没有登录,您不需要显示他们。否则,从它们中提取 BOOL 值,如下所示:

if (photoModelObject.voted && photoMobelObject.purchased) {
    BOOL isVoted = [photoModelObject.voted boolValue];
    BOOL isPurchased = [photoModelObject.purchased boolValue];

    // Use booleans to present info for registered users
} else {
    // There is no info about votes and purchasing provided for the current user
}
于 2017-04-02T11:06:22.177 回答