Obj-C easy method to convert from NSObject with properties to NSDictionary?

后端 未结 6 945
感情败类
感情败类 2020-12-07 17:17

I ran across something that I eventually figured out, but think that there\'s probably a much more efficient way to accomplish it.

I had an object (an NSObject which

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-07 17:54

    You also can use the NSObject+APObjectMapping category which is available on GitHub: https://github.com/aperechnev/APObjectMapping

    It's a quit easy. Just describe the mapping rules in your class:

    #import 
    #import "NSObject+APObjectMapping.h"
    
    @interface MyCustomClass : NSObject
    @property (nonatomic, strong) NSNumber * someNumber;
    @property (nonatomic, strong) NSString * someString;
    @end
    
    @implementation MyCustomClass
    + (NSMutableDictionary *)objectMapping {
      NSMutableDictionary * mapping = [super objectMapping];
      if (mapping) {
        NSDictionary * objectMapping = @{ @"someNumber": @"some_number",
                                          @"someString": @"some_string" };
      }
      return mapping
    }
    @end
    

    And then you can easily map your object to dictionary:

    MyCustomClass * myObj = [[MyCustomClass alloc] init];
    myObj.someNumber = @1;
    myObj.someString = @"some string";
    NSDictionary * myDict = [myObj mapToDictionary];
    

    Also you can parse your object from dictionary:

    NSDictionary * myDict = @{ @"some_number": @123,
                               @"some_string": @"some string" };
    MyCustomClass * myObj = [[MyCustomClass alloc] initWithDictionary:myDict];
    

提交回复
热议问题