Search code examples
iosmultithreadingcore-datansmanagedobjectnsmanagedobjectcontext

dispatch_async task problems with context


I am using a dispatch_async task to retrieve a list with some contacts.
When selecting a contact from this list, I call Storage Manager to retrive some further information for this contact.
I get the error: Illegal attempt to establish a relationship...between objects in different contexts.
How to solve this?
Here is my code:

 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
      sections = [self getContactList];
   });

informationList = [StorageManager getInfoForContact:[sections objectAtIndex:1]];

The error is at the line with informationList. Can someone help me to solve this?


Solution

  • I don't have the whole picture of your problem. However you are calling [self getContactList] into a async block. So, while [self getContactList] is executing the next line outside the block will be called. That means:

    informationList = [StorageManager getInfoForContact:[sections objectAtIndex:1]];
    

    is executed before:

    sections = [self getContactList];
    

    Probably your error is there.

    Try:

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        sections = [self getContactList];
        dispatch_sync(dispatch_get_main_queue(), ^{
            informationList = [StorageManager getInfoForContact:[sections objectAtIndex:1]];
        });
    });