I have some data consists of records for 2 tables: pairs and items. These tables are linked with many-to-many relationships. I see 2 possble ways to fill core data entities. Let we have already filled all the items and now we should fill pairs. In both cases "identifier" is an additional text property/field.
Way 1 (NSFetchRequest only):
//get data which should be converted to core data entities
id pairsInfoArray = ...;
for (id pairInfo in pairsInfoArray) {
//get items by identifier using NSFetchRequest
id item1 = ...;
id item2 = ...;
//create pair entity
id pair = ...;
pair.items = [NSSet setWithObjects:item1, item2, nil];
}
Way 2 (call NSFetchRequest one time only and use NSDictionary/NSMutableDictionary instead):
//get all items via NSFetchRequest
NSArray *itemsObjArray = ...;
//place all the items into array as key = item.identifier, value = item (as object)
NSMutableDictionary *itemsObjDict = ...;
//get data which should be converted to core data entities
id pairsInfoArray = ...;
for (id pairInfo in pairsInfoArray) {
//get items by key from itemsObjDict
id item1 = ...;
id item2 = ...;
//create pair entity
id pair = ...;
pair.items = [NSSet setWithObjects:item1, item2, nil];
}
All my data (not only items and pairs) are filled during 5 minutes (way1) and 45 seconds (way2). it is including time to perform [context save:nil]
.
As I see the second way works much faster than the first one. But has it any hidden disadvantages? For example wouldn't saving of items to an additional dictionary waste the memory?