I am trying to make loading multiple entities more manageable in code. The code below is attached to an object that can load over 1000 times, so I’ve put it in a loop and attached a manageable array of entities.
The problem is, because I have no idea if a key is available in singleObject, I am getting a crash on [singleObject valueForKey:@”actor”] when I am on the directors entity. It’s because the key “actor” doesn’t exist. See my code here.
NSArray *entities = [[NSArray alloc] initWithObjects: @"actors", @"directors", @"subtitles", @"audios", nil];
for (NSString *anEntity in entities)
{
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:anEntity inManagedObjectContext:context];
[request setEntity:entityDescription];
NSArray *objects = [context executeFetchRequest:request error:&error];
if (objects == nil) {
// error
}
for (NSManagedObject *singleObject in objects)
{
if (singleObject != nil)
{
if ([singleObject valueForKey:@"actor"] != nil)
{
[self.actors addObject:[singleObject valueForKey:@"actor"]];
}
else if ([singleObject valueForKey:@"director"] != nil)
{
[self.directors addObject:[singleObject valueForKey:@"director"]];
}
else if ([singleObject valueForKey:@"subtitle"] != nil)
{
[self.subtitles addObject:[singleObject valueForKey:@"subtitle"]];
}
else if ([singleObject valueForKey:@"audio"] != nil)
{
[self.audios addObject:[singleObject valueForKey:@"audio"]];
}
}
}
}
[entities release];
[request release];'
How can I make this code work, and be vastly expandable, without having to put a bunch of try/catches around everything?
OK I think I found a way that works for me using NSDictionary instead. It works in my situation simply because my entity names are plural (actors) and my attributes are singular (actor). Here is what I came up with:
Details:
I loop through the keys in the dictionary. I make them mutable so I can take the s off of the end of the key. Then I pull the value (which is an array) from that key and load the array using the key without the s.
Somewhat complicated to read the code, but really slims down the manageability. Now all I need to do is add a new plural entity with matching singular attribute and just add the key/value pair to the dictionary.