Browse Source

bugfix: Crash when convert `UIColor` to json. #46
When call [UIColor CIColor], it may throws an exception.
Catch the exception and ignore this value.

ibireme 9 năm trước cách đây
mục cha
commit
75629fa491
2 tập tin đã thay đổi với 16 bổ sung2 xóa
  1. 12 2
      YYModel/NSObject+YYModel.m
  2. 4 0
      YYModelTests/YYTestModelToJSON.m

+ 12 - 2
YYModel/NSObject+YYModel.m

@@ -1167,8 +1167,18 @@ static id ModelToJSONObjectRecursive(NSObject *model) {
         } else {
             switch (propertyMeta->_type & YYEncodingTypeMask) {
                 case YYEncodingTypeObject: {
-                    id v = ((id (*)(id, SEL))(void *) objc_msgSend)((id)model, propertyMeta->_getter);
-                    value = ModelToJSONObjectRecursive(v);
+                    /*
+                     When send the getter message to some object (for example:[[UIColor redColor] CIColor]),
+                     it may throws an exception.
+                     */
+                    @try {
+                        id v = ((id (*)(id, SEL))(void *) objc_msgSend)((id)model, propertyMeta->_getter);
+                        value = ModelToJSONObjectRecursive(v);
+                    }
+                    @catch (NSException *exception) {
+                        // Log the exception and ignore this value.
+                        NSLog(@"%@",exception);
+                    }
                     if (value == (id)kCFNull) value = nil;
                 } break;
                 case YYEncodingTypeClass: {

+ 4 - 0
YYModelTests/YYTestModelToJSON.m

@@ -10,6 +10,7 @@
 //
 
 #import <XCTest/XCTest.h>
+#import <UIKit/UIKit.h>
 #import "YYModel.h"
 #import "YYTestHelper.h"
 
@@ -53,6 +54,7 @@
 @property (nonatomic, strong) NSMutableDictionary *mDict;
 @property (nonatomic, strong) NSSet *set;
 @property (nonatomic, strong) NSMutableSet *mSet;
+@property (nonatomic, strong) UIColor *color;
 @end
 
 @implementation YYTestModelToJSONModel
@@ -107,12 +109,14 @@
     model.shortValue = 4;
     model.array = @[@1,@"2",[NSURL URLWithString:@"https://github.com"]];
     model.set = [NSSet setWithArray:model.array];
+    model.color = [UIColor redColor];
     
     NSDictionary *jsonObject = [model yy_modelToJSONObject];
     XCTAssert([jsonObject isKindOfClass:[NSDictionary class]]);
     XCTAssert([jsonObject[@"int"] isEqual:@(1)]);
     XCTAssert([jsonObject[@"long"] isEqual:@(2)] || [jsonObject[@"long"] isEqual:@(3)]);
     XCTAssert([ ((NSDictionary *)jsonObject[@"ext"])[@"short"] isEqual:@(4)]);
+    XCTAssert(jsonObject[@"color"] != nil);
     
     NSString *jsonString = [model yy_modelToJSONString];
     XCTAssert([[YYTestHelper jsonObjectFromString:jsonString] isKindOfClass:[NSDictionary class]]);