YYKit icon indicating copy to clipboard operation
YYKit copied to clipboard

关于 YYModelExample 中的 CustomMapperExample 打印结果为空

Open leejunhui opened this issue 5 years ago • 0 comments

@interface YYMessage : NSObject
@property (nonatomic, assign) uint64_t messageId;
@property (nonatomic, strong) NSString *content;
@property (nonatomic, strong) NSDate *time;
@end

@implementation YYMessage
+ (NSDictionary *)modelCustomPropertyMapper {
    return @{@"messageId":@"i",
             @"content":@"c",
             @"time":@"t"};
}
- (BOOL)modelCustomTransformFromDictionary:(NSDictionary *)dic {
    uint64_t timestamp = [dic unsignedLongLongValueForKey:@"t" default:0];
    self.time = [NSDate dateWithTimeIntervalSince1970:timestamp / 1000.0];
    return YES;
}
- (BOOL)modelCustomTransformToDictionary:(NSMutableDictionary *)dic {
    dic[@"t"] = @([self.time timeIntervalSince1970] * 1000).description;
    return YES;
}
@end

static void CustomMapperExample() {
    YYMessage *message = [YYMessage modelWithJSON:@"{\"i\":\"2000000001\",\"c\":\"Hello\",\"t\":\"1437237598000\"}"];
    NSString *messageJSON = [message modelToJSONString];
    NSLog(@"Book: %@", messageJSON);
}

修改了 modelCustomTransformToDictionary 方法的返回类型,并且加入了返回值为 YES 后,在 CustomMapperExample 静态方法中打印结果将正常显示。

具体原因如下图所示

1

2

在对 model 调用 modelToJSONString 方法后,其调用栈如下:

modelToJSONString -> modelToJSONData -> modelToJSONObject -> ModelToJSONObjectRecursive ,最终在 定位到

    if (modelMeta->_hasCustomTransformToDictionary) {
        BOOL suc = [((id<YYModel>)model) modelCustomTransformToDictionary:dic];
        if (!suc) return nil;
    }

说明框架判断如果对象实现了 modelCustomTransformToDictionary:dic 方法,如果这个方法返回值为 NO,那么就会返回空值,从而导致最后的 json 字符串返回为空。

leejunhui avatar Mar 19 '20 12:03 leejunhui