Skip to content

Instantly share code, notes, and snippets.

@hamada147
Last active June 10, 2018 13:52
Show Gist options
  • Save hamada147/0ff791ca12d94bd952880b2bbe858cf0 to your computer and use it in GitHub Desktop.
Save hamada147/0ff791ca12d94bd952880b2bbe858cf0 to your computer and use it in GitHub Desktop.
Create NSObject in runtime from an array of NSDictionary
- (NSArray *)getRecrodsFromDictionary: (NSDictionary*)dictionary {
// the following include the array that I want to turn into objects
NSArray * response = [self parseKey:@"responseDetails" fromDictionary:dictionary];
NSMutableArray * rows = [[NSMutableArray alloc] init];
if ([response count] != 0) {
// 1. get all NSDictionary keys
NSDictionary * temp = response[0];
NSArray * keys = [temp allKeys];
// 2. create a class
Class ModelClass = objc_allocateClassPair([NSObject class], "WidgetDetailsModel", 0);
// 3. all class variables with the same name as key retrieved from NSDictionary
for (NSString * key in keys) {
const char * name = [key cStringUsingEncoding:NSASCIIStringEncoding];
class_addIvar(ModelClass, name, sizeof(id), rint(log2(sizeof(id))), @encode(NSString));
}
// 4. register a class to be used
objc_registerClassPair(ModelClass);
for (NSDictionary * curr in response) {
// create object
id MC = [[ModelClass alloc] init];
for (NSString * key in keys) {
// set values
const char * name = [key cStringUsingEncoding:NSASCIIStringEncoding];
Ivar CurrVar = class_getInstanceVariable(ModelClass, name);
NSString * newValue = [curr objectForKey: key];
object_setIvar(MC, CurrVar, newValue);
}
// add object to array
[rows addObject:MC];
}
}
return [rows copy];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment