Search code examples
jsoncore-datansdictionarynsmanagedobjectcontextmagicalrecord

How I can map NSDictionary to NSManagedObject without writing to CoreData?


I use a MagicalRecord, and am having a little trouble using it.

A server sends me a JSON, and I need it as quickly as possible ro map to the existing NSManagedObject and give it to the block.

NSManagedObjectContext *localContext = [NSManagedObjectContext MR_contextForCurrentThread];
[Review MR_importFromObject:dictionary inContext:localContext];
[localContext MR_saveOnlySelfAndWait];

And after:

[[CacheOperation sharedOperation]saveBestRateProductByDict:reviewDict];
Review *review = [Review MR_findFirstByAttribute:@"id" withValue:[reviewDict objectForKey:@"id"]];

But if I have many objects, it takes a lot of time.

How I can map NSDictionary to NSManagedObject without writing to CoreData?


Solution

  • I guess MR_importFromObject check for the existence of the object to have an insert or update behavior.

    That's great for most cases. (and it was made for the 90% http://www.cimgf.com/2012/05/29/importing-data-made-easy/ ) But you are in the 10% (me too, if it can be of any support)

    This behavior mean that there is a request to find the object, and a request to update it. Multiple by the number of objects, that can be huge.

    You can refer to a good apple doc (the part Implementing Find-or-Create Efficiently ) :

    https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/CoreData/Articles/cdImporting.html

    One trick is to make only one request for all the objects you want to update, and one request to update them all. It's worse in memory usage but better in I/O, that should speed you up.

    We went another way using TMCache and storing raw JSON for objects changing frequently.

    Hope this help.