IOS reflection: converts an object to NSDictionary and iosnsdictionary.
In IOS network programming, we usually need to save some Entity Data to NSDictionary, after obtaining NSDictionary, you can directly use the NSJSONSerialization-type dataWithJSONObject method after iOS 5 to return NSData objects containing JSON strings. Then, call ASIHttpRequest.
If a class attribute contains other classes or more Nested classes, it will be very complicated to write it by yourself. Here we can write it through reflection, the basic idea is to get the attribute name through reflection and get the value through KVC. The rest is the nested loop of NSDictionary and NSArray.
IOS reflection reference <objc/runtime. h>. Use class_copyPropertyList and property_getName
Reflection details Official Website: Click
Sample Code
#import <Foundation/Foundation.h>@interface BIDObjectToNsDictionary : NSObject+ (NSDictionary*)getObjectData:(id)obj;@end
# Import "BIDObjectToNsDictionary. h "# import <objc/runtime. h> + (NSDictionary *) getObjectData :( id) obj {NSMutableDictionary * dic = [NSMutableDictionary dictionary]; unsigned int propsCount; optional * props = class_copyPropertyList ([obj class], & propsCount); // obtain the attribute list for (int I = 0; I <propsCount; I ++) {objc_property_t prop = props [I]; NSString * propName = [NSString stringwithuf8string: property_getName (prop)]; // obtain the attribute name id value = [obj valueForKey: propName]; // kvc read value if (value = nil) {value = [NSNull null];} else {value = [self getObjectInternal: value]; // custom processing array, dictionary, other classes} [dic setObject: value forKey: propName];} return dic;} + (id) getObjectInternal :( id) obj {if ([obj isKindOfClass: [NSString class] | [obj isKindOfClass: [NSNumber class] | [obj isKindOfClass: [NSNull class]) {return obj;} if ([obj isKindOfClass: [NSArray class]) {NSArray * objarr = obj; NSMutableArray * arr = [NSMutableArray arrayWithCapacity: objarr. count]; for (int I = 0; I <objarr. count; I ++) {[arr setObject: [self getObjectInternal: [objarr objectAtIndex: I] atIndexedSubscript: I];} return arr;} if ([obj isKindOfClass: [NSDictionary class]) {NSDictionary * objdic = obj; NSMutableDictionary * dic = [NSMutableDictionary dictionaryWithCapacity: [objdic count]; for (NSString * key in objdic. allKeys) {[dic setObject: [self getObjectInternal: [objdic objectForKey: key] forKey: key]; // parse the dictionary type, recursively call} return dic ;} return [self getObjectData: obj]; // parses other classes and recursively calls @ end
Reference Original article http://ios.9tech.cn/news/2013/0918/28899.html