1

I'm starting in coreData, and I have a doubt.

I have an App that reads data from a server, I parse the data, and get as NSDictionary of Objects.

To save the data to coreData, i do the following:

    for (NSDictionary *activityData in arrayWithResult){
        [CompanyActivity createActivityWithInfoFromServer:activityData inManagedObjectContext:self.managedObjectContext];
    }

    if (![self.managedObjectContext save:&error])
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);

This reads about 300 records. The method 'createActivityWithInfoFromServer:' checks if there is any record with that name. If so, updates the data, if not, creates one.

The problem is that, while the "for" cycle is running, if i interact with the user interface, it stops saving in core data, sometimes, not always. Why?

If I take the SAVE inside the cycle, the problem disappears.

What should I do?

Thanks all,

RL

Rui Lopes
  • 2,562
  • 6
  • 34
  • 49
  • What do you mean "it stops saving"? Do you get an error? Do objects get created but not saved? – TechZen Aug 16 '11 at 21:26
  • No error. I have a NSLog, and it stops logging, and objects are not created. Sometimes, it create 168, other times, 230... other times, all of them... – Rui Lopes Aug 16 '11 at 21:29
  • Do you mean that the `arrayWithResult` has x number of entries but only y number of managed objects get saved? How do you know how many objects should be created and saved if some dictionaries may have duplicates already in Core Data? – TechZen Aug 16 '11 at 22:16
  • Yes that's it. I have a NSLog that tells me if the object is created or updated. If I reset the iPhone simulator, all of them are created as new ones. – Rui Lopes Aug 17 '11 at 08:32

1 Answers1

0

Depending on what your reasoning is to still allow the user to interact with the UI, you could either disable the UI for that time, or create a new thread that handles the piece of code that you posted.

As for the reasoning why it only fails to save sometimes, I assume that sometimes it doesn't have to create as many new objects and finishes sooner, and can save before you interact with the UI. If you save inside the for loop than you are saving everything after looking at each item which is fairly inefficient.

Karoly S
  • 3,180
  • 4
  • 35
  • 55
  • to create a thread for that job, like this: dispatch_queue_t registerDeviceQueue = dispatch_queue_create("RegisterDevice", NULL); dispatch_async(registerDeviceQueue, ^{ for (NSDictionary *activityData in arrayWithResult){ [CompanyActivity createActivityWithInfoFromServer:activityData inManagedObjectContext:self.managedObjectContext]; } }); dispatch_release(registerDeviceQueue); – Rui Lopes Aug 16 '11 at 21:50
  • Yea, it looks like you've got the right idea, if you want more material this question seems to cover it fairly well: http://stackoverflow.com/questions/3869217/iphone-ios-running-in-separate-thread – Karoly S Aug 16 '11 at 21:56