Skip to content

threading

Marian Paul edited this page Feb 23, 2016 · 1 revision

By default, there is no threading concept into WAMapping. Again, this is to keep the library as much usable for your needs as possible.

However, mapping to a separate thread is really easy. You juste have to dispatch the mapping to a secondary thread:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    [mapper mapFromRepresentation:json
                          mapping:enterpriseMapping
                       completion:^(NSArray *mappedObjects) {
                           dispatch_async(dispatch_get_main_queue(), ^{
                              // Update the UI with the mapped data
                           });
                       }];

If you use the CoreData store, you need to be careful about contexts. Remember, CoreData is not thread safe. You have to create a local context for your thread, save and merge the changes to go back to the main thread. Then, the NSManagedObject instances are not thread safe as well, but their object IDs are.

By using MagicalRecord:

MagicalRecord saveWithBlock:^(NSManagedObjectContext * _Nonnull localContext) {
    WACoreDataStore *store = [[WACoreDataStore alloc] initWithManagedObjectContext:localContext];
    WAMapper *mapper = [[WAMapper alloc] initWithStore:store];
    
    [mapper mapFromRepresentation:json
                          mapping:enterpriseMapping
                       completion:
     ^(NSArray *mappedObjects) {
         
     }];
}
                  completion:
 ^(BOOL contextDidSave, NSError * _Nullable error) {
     // You are on main thread
 }];
Clone this wiki locally