Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IOS CoreData, which NSManagedObjectContextConcurrencyType to use and why?

I can't make any sense out of the documentation for NSManagedObjectContextConcurrencyType. Which type would I use for the following situation, and why?

- (void)viewDidLoad
{
    self.managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:???];
    [self loadRecordsFromCoreData];
}


- (void)loadRecordsFromCoreData {

[self.managedObjectContext performBlockAndWait:^{
    //[self.managedObjectContext reset]; //do I need to do this?
    NSError *error = nil;
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Item"];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"display == YES"];
    [request setPredicate:predicate];
    [request setSortDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"order" ascending:YES]]];

    self.items = nil;
    self.items = [self.managedObjectContext executeFetchRequest:request error:&error];

}];

[self displayItems];
}

-displayItems will display views based on the properties of the objects in the self.items array, such as item.image, item.title, item.descriptionText, etc.

like image 340
soleil Avatar asked Oct 07 '22 15:10

soleil


1 Answers

NSMainQueueConcurrencyType.

UI events, such as view did load, take place on the main thread. You'll be manipulating your objects on the main thread (self.items in this case), so you should ensure that they are fetched into the context / saved on that thread as well.

NSPrivateQueueConcurrencyType is for contexts whose work is to be done on a background thread.

like image 113
ImHuntingWabbits Avatar answered Oct 10 '22 01:10

ImHuntingWabbits