0

我试图以 1000 的间隔保存 MOC,但是下面的代码似乎错过了其中的一些。这只拯救了2/3的物体,其余的似乎消失在了深渊中。这似乎是实现这一目标的一种笨拙方式,所以如果有人能提出更好的方法,我很乐意听到。

此方法也需要大约 9 分钟来添加 115,000 个对象。我能做些什么来改善这一点吗?谢谢。

dispatch_async(backgroundDispatchQueue,{

 NSManagedObjectContext *backgroundThreadContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSConfinementConcurrencyType];
 [backgroundThreadContext setPersistentStoreCoordinator:self.persistentStoreCoordinator];
 [backgroundThreadContext setUndoManager:nil];


 [products enumerateObjectsUsingBlock:^(id product, NSUInteger idx, BOOL *stop) {


   NSManagedObject* newProduct;
   newProduct = [NSEntityDescription insertNewObjectForEntityForName:@"Products" inManagedObjectContext:backgroundThreadContext];

   [newProduct setValue:[product valueForKey:@"product_name"] forKey:@"name"];
   [newProduct setValue:[product valueForKey:@"product_codes"] forKey:@"codes"];

   if ([product valueForKey:@"information"] == (id)[NSNull null]){
                                   // No information, NULL
     [newProduct setValue:@"" forKey:@"information"];
   } else {
     NSString *information = [product valueForKey:@"information"];
     [newProduct setValue:information forKey:@"information"];

   }

   if ([product valueForKey:@"megaimportant"] == (id)[NSNull null]){
                                       // No information, NULL
     [newProduct setValue:@"" forKey:@"megaimportant"];
   } else {
     NSString *megaimportant = [product valueForKey:@"megaimportant"];
     [newProduct setValue:megaimportant forKey:@"megaimportant"];

   }

   if ((self.productDBCount % 1000) == 0){
     NSLog(@"SAVE ME");
     NSError *error;

     if(![backgroundThreadContext save:&error])
     {
       NSLog(@"There was a problem saving the context (add/update). With error: %@, and user info: %@",
         [error localizedDescription],
         [error userInfo]);
     }
   } else if ((self.productDBCount + 1) == self.totalCount){
     NSLog(@"Final Save");

     NSError *error;

     if(![backgroundThreadContext save:&error])
     {
       NSLog(@"There was a problem saving the context (add/update). With error: %@, and user info: %@",
         [error localizedDescription],
         [error userInfo]);
     }
   }



   dispatch_async(dispatch_get_main_queue(), ^
   {

    self.productDBCount = self.productDBCount + 1;
    float progress = ((float)self.productDBCount / (float)self.totalCount);
    int percent = progress * 100.0f;
    self.downloadUpdateProgress.progress = progress;
    self.percentageComplete.text = [NSString stringWithFormat:@"%i", percent];
    NSLog(@"Added / updated product %f // ProductDBCount: %i // Percentage progress: %i // Total Count: %i", progress, self.productDBCount, percent, self.totalCount);

    NSDate *currentProcessedDate = [NSDate date];
    NSTimeInterval timeSinceStarted = [currentProcessedDate timeIntervalSinceDate:self.startProcessing];
    NSInteger remainingProcesses = self.totalCount - self.productDBCount;
    float timePerProcess = timeSinceStarted / (float)self.productDBCount;
    float remainingTime = timePerProcess * (float)remainingProcesses;
    self.timeRemaining.text = [NSString stringWithFormat:@"ETA: %0.0f minutes %0.0f seconds", (((float)remainingTime - fmodf(remainingTime, 60.0f))/60), fmodf(remainingTime, 60.0f)];

    if (self.productDBCount == self.totalCount){

      [self updatesCompleted:[jsonArray valueForKey:@"last_updated"]];
    }

                                                 });
}];

});
4

1 回答 1

1

在您在后台队列上调度的块的末尾,您异步地在主队列上调度另一个块。在那里你增加你的 self.productDBCount。但同时您在后台队列上使用此属性。

因此,您在循环的下一次迭代中的背景块可能不会增加值(因为主队列上的块尚未执行)并对此做出错误的决定。更糟糕的是,如果这个属性被声明为非原子的,它甚至会得到一个损坏的值(尽管让它成为原子并不能解决这个竞争条件)。

尝试用同步调用替换异步调用:dispatch_sync(dispatch_get_main_queue()...

为了使内存上的导入更容易,您可能还希望在保存每个批次后重置上下文。但是您需要确保在重置后不使用在此上下文中创建的任何对象。

如果您想查看导入过程中花费最多的时间,请在 Instruments 中运行它。我可以推荐将 Core Data 工具与 Time Profiler 工具结合使用。Core Data 工具仅在模拟器中可用。

于 2013-07-12T11:48:22.520 回答