Core Data memory usage while importing large dataset

前端 未结 3 637
你的背包
你的背包 2021-02-04 16:28

I\'m now stuck for about two weeks with a nasty Core Data problem. I read lots of blogpost, articles and SO questions/answers but I\'m still not able to solve my problem.

<
3条回答
  •  忘了有多久
    2021-02-04 16:45

    I have an import helper that does something very similar.

    Have a look at the code below and see if it helps you

    __block NSUInteger i = 0;
    NSArray *jsonArray = ...
    for (NSDictionary *dataStucture in jsonArray)
    {
        [managedObjectContext performBlock:^{
            @autoreleasepool {
                i++;
                A *a = (A*)[self newManagedObjectOfType:@"A" inManagedObjectContext:managedObjectContext];
                [self parseData:[dataStucture objectForKey:@"a"]
                     intoObject:a
         inManagedObjectContext:managedObjectContext];
    
                [managedObjectContext refreshObject:a
                                       mergeChanges:YES];
                if (i > 20) // Arbitrary number here
                {
                    NSError *error = nil;
                    [managedObjectContext save:&error];
                    [managedObjectContext reset];
                }
    
                [managedObjectContext refreshObject:a
                                       mergeChanges:YES];
    
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self saveMainThreadManagedObjectContext];
    
                NSLog(@"DONE");
                // parsing is done, now you see that there are still
                // A's, B's and C's left in memory.
                // Every managedObjectContext is saved and no references are kept
                // to any A, B and C so they should be released. This is not true,
                // so a managedObjectContext is keeping a strong reference to these
                // objects.
            });
        }];
    }
    

提交回复
热议问题