100% CPU in Core Data operation


How it is possible that i get CPU 100% and block main thread in background queue. I do it like that:

Firstly i create context in custom setter:

-(void)setContext:(NSManagedObjectContext *)context {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
        _context = context;

Then I download some data using NSURLConnectionDataDelegate and then is my method to inserting:

-(void)connectionDidFinishWithObject:(NSArray*)arrayOfObjects {

    dispatch_queue_t fetchQ = dispatch_queue_create("myDispatch", NULL);
    dispatch_async(fetchQ, ^{
                [self.context performBlock:^{
                    for(NSDictionary *dic in myArr) {
                        [Tournament  tournamentWithDictionary:dic inMOC:self.context];


And here is my insert to NSManagedObject subclass:

+(Tournament*)tournamentWithDictionary:(NSDictionary*)dictionary inMOC:(NSManagedObjectContext*)moc {
 Tournament *finalElement;   

    if(!finalElement) {
        finalElement = [NSEntityDescription insertNewObjectForEntityForName:@"Tournament" inManagedObjectContext:moc];
        [finalElement setTournamentID:[NSNumber numberWithInt:[[dictionary objectForKey:@"ID"] integerValue]]];
    return finalElement;

And I'm getting 100% CPU usage and my interface is block! Why?!

Did you actually profile your code to see what is consuming the CPU?

Also, how is your managed object context configured? Specifically, what is the concurrency type? Your use of a queue to cause the context to perform a block is going to be entirely pointless if the concurrency type is NSMainQueueConcurrencyType.

I'd suggest you read this documentation closely.

Your use of that dispatch_async in the setter is both unnecessary and it will lead to a race condition with the use dispatch_async to a different queue in connectionDidFinishWithObject:.

I.e. your concurrency is busted.