IOS custom type conversion to Dictionary

Source: Internet
Author: User

IOS Custom Model If you want to convert bit JSON to interact with the server, I convert the model data type first to dictionary and then JSON serialization.

#import <objc/runtime.h>


@implementation Converttocustomclass
+ (Nsmutablearray *) Convertcustomclasstodictionary: (Nsmutablearray *) array{
Nsmutablearray *customarray = [Nsmutablearray array];
For (ID customclass in array) {
NSString *classname = Nsstringfromclass ([Customclass class]);//Get class name
const char *cclassname = [ClassName utf8string];//class name encoding method
ID theclass = Objc_getclass (cclassname);//Get current class type
unsigned int outcount, I;

Get all the properties of the class
objc_property_t *properties = class_copypropertylist (Theclass, &outcount);
Nsmutablearray *propertynames = [[Nsmutablearray alloc] initwithcapacity:1];
for (i = 0; i < Outcount; i++) {
objc_property_t property = Properties[i];
Property_getname () returns the name of the property
NSString *propertynamestring = [[NSString alloc] Initwithcstring:property_getname (property) Encoding: Nsutf8stringencoding];
[PropertyNames addobject:propertynamestring];
Property_getattributes () returns the properties of the property
NSLog (@ "%s%s\n", Property_getname (property), property_getattributes);
}
Nsmutabledictionary *finaldict = [[Nsmutabledictionary alloc] initwithcapacity:1];
For (NSString *key in PropertyNames)
{
SEL Mysel = nsselectorfromstring (key);
ID value = [customclass Performselector:mysel];
if (value = = nil)
{
value = [NSNull null];
}
[Finaldict Setobject:value Forkey:key];
NSLog (@ "%@%@\n", value, key);
}
[Customarray addobject:finaldict];
}
return Customarray;} @end

IOS custom type conversion to Dictionary

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.