2012-09-17 18 views
1

我的核心數據代碼的時間太長,所以我評論了大部分的線路,它簡化了這個:爲什麼添加單個實體後,我的核心數據需要很長時間才能保存?

NSString *storePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"CoreDataStore.sqlite"]; 
    NSString *backupSourceStorePath = [[self applicationDocumentsDirectory] 
             stringByAppendingPathComponent:@"CoreDataStoreBackup.sqlite"]; 

    NSManagedObjectContext *oldContext = [self version1ManagedObjectContext]; 
    TICDSSynchronizedManagedObjectContext *newContext = [self managedObjectContext]; 
    NSFetchRequest *oldFetchRequest = [[NSFetchRequest alloc] init]; 
    NSEntityDescription *oldEntryEntity = [NSEntityDescription entityForName:@"Entry" 
                 inManagedObjectContext:oldContext]; 

    [oldFetchRequest setEntity:oldEntryEntity]; 

    int numberOfEntries = [oldContext countForFetchRequest:oldFetchRequest error:nil]; 

    int batchSize = 10; 
    [oldFetchRequest setFetchLimit:batchSize]; 
    int offset = 0; 

    while (numberOfEntries - offset > 0) { 

     [oldFetchRequest setFetchOffset:offset]; 
     NSError *error; 
     NSArray *entries = [oldContext executeFetchRequest:oldFetchRequest error:&error]; 

     int i = 0; 
     for (NSManagedObject *entry in entries) { 

      Entry *newEntry = [NSEntityDescription insertNewObjectForEntityForName:@"Entry" 
                  inManagedObjectContext:newContext]; 
      i++; 
      NSLog(@"i: %i", i); 
     } 

     [newContext save:&error]; 

     NSLog(@"Save error: %@", error); 

     offset = offset + batchSize; 

    } 

如果我沒有在那裏insertNewObjectForEntityForName線,節省用不了多久在所有。但是就這一點而言,節省大約需要一分鐘。在此之前,數據存儲中沒有別的東西。任何可能發生這種情況的原因?

+0

你的意思是行'[newContext節省:錯誤]'走大約一分鐘?另外,你能否評論你正在做的事情的上下文 - 將託管對象從一個上下文複製到另一個上下文? – FluffulousChimp

+0

正確,該行需要大約一分鐘的時間。基本上,我正在複製它們。這是使用大型數據庫進行標準遷移的唯一方法。如果通過自動映射完成,它會耗盡內存並在一段時間後死亡。所以我必須手動完成。 – Andrew

回答

0

[newContext save:&error]; 

之外循環。每次運行都不需要。

它會解決您的問題。

0

我同意把它放在循環之外,不僅僅是爲了執行目的(速度),而是因爲如果循環中出現錯誤,你希望保存一半還是保存數據,然後另一半不保存?大多數時候,用戶期望全部或者沒有,其他方面你可以作爲代碼來確定哪些條目正確保存,哪些條目沒有保存。

所以1 ..執行時間 和2.管理目的

相關問題