我的核心数据代码耗时太长,所以我注释掉了大部分行,将其简化为:
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
线路,那么保存根本不需要很长时间。但是有了这条线,保存大约需要一分钟。在此之前,数据存储中没有其他内容。为什么会发生这种情况?