开发者

Convert an object into NSDictionary

Is there any generic implementation which converts any Object into NSDictionary开发者_运维问答, sets all variable names as keys and values as dictionary values?


In order to achieve your objective, you can use Key-Value Coding. This protocol provides a mechanism to set values of object properties based on the names of the properties represented as NSString's rather than calling the accessors directly.

In order for it to work, you need to have defined your objects with accessors that follow the naming conventions (easy enough using properties). You can see the NSKeyValueCoding protocol guide here:

http://bit.ly/es6kyH

And the Key-Value Coding programming guide here:

http://bit.ly/fBY3Qa

You'll still have to do the iteration, but it's a good start.


Solved using SBJSONParser, converted NSObject to JSON Representation and then fetched NSDictionary out of it.


The perfect way to do this is by using a library for serialization/deserialization many libraries are available but one i like is JagPropertyConverter https://github.com/jagill/JAGPropertyConverter

it can convert your Custom object into NSDictionary and vice versa

Assuming

@interface Person : NSObject

@property (nonatomic, retain) NSNumber * age
@property (nonatomic, retain) NSString * address
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSString * cellNo;

@end

JAGPropertyConverter *converter = [[JAGPropertyConverter alloc]init];
converter.classesToConvert = [NSSet setWithObjects:[Person class], nil];

Person *person = [[Person alloc]init];
person.name = @"name";
person.address = @"address";
person.age = @27;
person.cellNo = @"XXXXXXXXXX";

//For Object to Dictionary 
NSDictionary *dictPerson = [converter convertToDictionary:person];


//For Dictionary to Object 
Person *person = [[Person alloc]init];
[converter setPropertiesOf:person fromDictionary:dictPerson];


No, you could have everything in your class, e.g. references to other objects and primitives. NS-Dictionary can serialize itself to a NSString and NSString can recreate the dictionary from the string. Best will be you supply your own methods to serialize it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜