Save a lot of code by using NSClassFromString in Objective C (二)

2014-11-24 00:59:32 · 作者: · 浏览: 10
e can generate the entity object with below method directly. It is very helpful.
NSManagedObject *newObject = [NSEntityDescription insertNewObjectForEntityForName:name inManagedObjectContext:context];

}

Here is the full code on my implementation, some methods are my wrapped internal method for the CoreData, which are not exposed here. But it will be very help for the reader to see how did I insert the entity :

// populates the ListEntity store with the values from the json object dict
+ (void)populateEntity: (id)dict withMetadata:(id)metadata withContext:(NSManagedObjectContext*) context {
bool isTombstone = [Utils isDeleted:metadata];

NSString *uri = [metadata valueForKey:@"uri"];
NSMutableDictionary *pKeys = [NSMutableDictionary dictionary];
NSString *tableName = nil;


NSArray *sub = [uri componentsSeparatedByString:@".svc/"];

if ([sub count] == 2) {
uri = [sub objectAtIndex:1];
NSArray *subStrings = [uri componentsSeparatedByString:@"("];

if ([subStrings count] == 2) {
tableName = [subStrings objectAtIndex:0];

// (Robert #) in Heat3, the table name is capitalized. So need special convert it here.
tableName = [NSString stringWithFormat:@"%@%@",[tableName substringToIndex:1].uppercaseString, [tableName substringFromIndex:1]];

NSString *keys = [[subStrings objectAtIndex:1] stringByReplacingOccurrencesOfString:@")" withString:@""];

NSArray *subKeys = [keys componentsSeparatedByString:@","];

for (NSString *key in subKeys) {
NSArray *keyPair = [key componentsSeparatedByString:@"="];
if ([keyPair count] == 2) {
[pKeys setObject:[keyPair objectAtIndex:1] forKey: [keyPair objectAtIndex:0]];
}
}
}

} else {
NSLog(@"Something is wrong, please check.");
}

if (nil != tableName && [pKeys allKeys] > 0)
{
NSManagedObject *newObject = nil;

// measure = [TgMeasure findFirstByAttribute:@"MeasureID" withValue:[dict valueForKey:@"MeasureID"]];

if (NSClassFromString(tableName)) {

NSString *string = [NSString string];
for (NSString *key in [pKeys allKeys]) {

if ([string length] == 0) {
string = [string stringByAppendingFormat:@"%@=%@", key, [pKeys objectForKey:key]];
} else {
string = [string stringByAppendingFormat:@" and %@=%@", key, [pKeys objectForKey:key]];
}

}

NSPredicate *predicate = [NSPredicate predicateWithFormat:string];

Class cls = NSClassFromString(tableName);
if (cls != Nil)
{
newObject = [cls findFirstWithPredicate:predicate];
}

}

// if its deleted and we have not seen it ignore it
// else delete it
if (isTombstone && newObject != nil)
{
[context deleteObject:newObject];
}
else if (!isTombstone)
{

[NSManagedObject createManagedObjectFromDictionary:dict inContext:CONTEXT_FOR_CURRENT_THREAD withName:tableName];