ios 多遍核心数据迁移的示例或解释?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5995231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Example or explanation of Core Data Migration with multiple passes?
提问by Jason
My iPhone app needs to migrate its core data store, and some of the databases are quite large. Apple's documentation suggests using "multiple passes" to migrate data to reduce memory use.However, the documentation is very limited and doesn't explain very well how to actually do this. Can someone either point me towards a good example, or explain in detail the process of how to actually pull this off?
我的 iPhone 应用程序需要迁移其核心数据存储,并且一些数据库非常大。Apple 的文档建议使用“多次通过”来迁移数据以减少内存使用。但是,文档非常有限,并没有很好地解释如何实际执行此操作。有人可以给我指出一个很好的例子,或者详细解释如何实际实现这一点的过程吗?
回答by Nick Weaver
I've figured out what Apple hints in their documentation. It's actually very easy but a long way to go before it's obvious. I'll illustrate the explanation with an example. The initial situation is this:
我已经弄清楚 Apple 在他们的文档中暗示了什么。这实际上很容易,但在它变得明显之前还有很长的路要走。我将举例说明。初始情况是这样的:
Data Model Version 1
数据模型版本 1
It's the model you get when you create a project with the "navigation based app with core data storage" template. I compiled it and did some hard hitting with some help of a for loop to create around 2k entries all with some different values. There we go 2.000 events with an NSDate value.
这是您使用“具有核心数据存储的基于导航的应用程序”模板创建项目时获得的模型。我编译了它,并在 for 循环的帮助下做了一些努力,以创建大约 2k 个条目,所有条目都具有一些不同的值。那里有 2.000 个带有 NSDate 值的事件。
Now we add a second version of the data model, which looks like this:
现在我们添加数据模型的第二个版本,如下所示:
Data Model Version 2
数据模型版本 2
The difference is: The Event entity is gone, and we've got two new ones. One which stores a timestamp as a double
and the second one which should store a date as NSString
.
不同之处在于: Event 实体消失了,我们有了两个新实体。一个将时间戳存储为 a double
,第二个应将日期存储为NSString
。
The goal is to transfer all Version 1Events to the two new entities and convert the values along the migration. This results in twice the values each as a different type in a separate entity.
目标是将所有版本 1事件传输到两个新实体并在迁移过程中转换值。这导致值的两倍,每个值都作为单独实体中的不同类型。
To migrate, we choose migration by hand and this we do with mapping models. This is also the first part of the answer to your question. We will do the migration in two steps, because it's taking long to migrate 2k entries and we like to keep the memory footprint low.
为了迁移,我们选择手动迁移,我们使用映射模型进行迁移。这也是你的问题答案的第一部分。我们将分两步进行迁移,因为迁移 2k 条目需要很长时间,而且我们希望保持较低的内存占用。
You could even go ahead and split these mapping models further to migrate only ranges of the entities. Say we got one million records, this may crash the whole process. It's possible to narrow the fetched entities down with a Filter predicate.
您甚至可以进一步拆分这些映射模型以仅迁移实体的范围。假设我们有 100 万条记录,这可能会导致整个过程崩溃。可以使用Filter predicate缩小获取的实体的范围。
Back to our two mapping models.
回到我们的两个映射模型。
We create the first mapping model like this:
我们像这样创建第一个映射模型:
1. New File -> Resource -> Mapping Model
1.新建文件->资源->映射模型
2. Choose a name, I chose StepOne
2.选择一个名字,我选择了StepOne
3. Set source and destination data model
3. 设置源数据模型和目标数据模型
Mapping Model Step One
映射模型第一步
The multi pass migration doesn't need custom entity migration policies, however we will do it to get a bit more detail for this example. So we add a custom policy to the entity. This is always a subclass of NSEntityMigrationPolicy
.
多通道迁移不需要自定义实体迁移策略,但是我们将这样做以获取此示例的更多详细信息。因此,我们向实体添加了自定义策略。这始终是 的子类NSEntityMigrationPolicy
。
This policy class implements some methods to make our migration happen. However it's simple in this case so we will have to implement only one method: createDestinationInstancesForSourceInstance:entityMapping:manager:error:
.
这个策略类实现了一些方法来使我们的迁移发生。然而,在这种情况下它很简单,所以我们只需要实现一种方法:createDestinationInstancesForSourceInstance:entityMapping:manager:error:
.
The implementation will look like this:
实现将如下所示:
StepOneEntityMigrationPolicy.m
StepOneEntityMigrationPolicy.m
#import "StepOneEntityMigrationPolicy.h"
@implementation StepOneEntityMigrationPolicy
- (BOOL)createDestinationInstancesForSourceInstance:(NSManagedObject *)sInstance
entityMapping:(NSEntityMapping *)mapping
manager:(NSMigrationManager *)manager
error:(NSError **)error
{
// Create a new object for the model context
NSManagedObject *newObject =
[NSEntityDescription insertNewObjectForEntityForName:[mapping destinationEntityName]
inManagedObjectContext:[manager destinationContext]];
// do our transfer of nsdate to nsstring
NSDate *date = [sInstance valueForKey:@"timeStamp"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
// set the value for our new object
[newObject setValue:[dateFormatter stringFromDate:date] forKey:@"printedDate"];
[dateFormatter release];
// do the coupling of old and new
[manager associateSourceInstance:sInstance withDestinationInstance:newObject forEntityMapping:mapping];
return YES;
}
Final step: the migration itself
最后一步:迁移本身
I'll skip the part for setting up the second mapping model which is almost identical, just a timeIntervalSince1970 used to convert the NSDate to a double.
我将跳过设置几乎相同的第二个映射模型的部分,只是用于将 NSDate 转换为 double 的 timeIntervalSince1970。
Finally we need to trigger the migration. I'll skip the boilerplate code for now. If you need it, I'll post here. It can be found at Customizing the Migration Processit's just a merge of the first two code examples. The third and last part will be modified as follows: Instead of using the class method of the NSMappingModel
class mappingModelFromBundles:forSourceModel:destinationModel:
we will use the initWithContentsOfURL:
because the class method will return only one, maybe the first, found mapping model in the bundle.
最后我们需要触发迁移。现在我将跳过样板代码。如果你需要它,我会在这里发布。它可以在自定义迁移过程中找到,它只是前两个代码示例的合并。第三部分也是最后一部分将修改如下:我们将使用NSMappingModel
类的类方法而不是类方法,因为类方法将只返回一个,可能是第一个,在包中找到的映射模型。mappingModelFromBundles:forSourceModel:destinationModel:
initWithContentsOfURL:
Now we've got the two mapping models which can be used in every pass of the loop and send the migrate method to the migration manager. That's it.
现在我们有了两个映射模型,它们可以在循环的每一次传递中使用,并将 migrate 方法发送到迁移管理器。就是这样。
NSArray *mappingModelNames = [NSArray arrayWithObjects:@"StepOne", @"StepTwo", nil];
NSDictionary *sourceStoreOptions = nil;
NSURL *destinationStoreURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreDataMigrationNew.sqlite"];
NSString *destinationStoreType = NSSQLiteStoreType;
NSDictionary *destinationStoreOptions = nil;
for (NSString *mappingModelName in mappingModelNames) {
NSURL *fileURL = [[NSBundle mainBundle] URLForResource:mappingModelName withExtension:@"cdm"];
NSMappingModel *mappingModel = [[NSMappingModel alloc] initWithContentsOfURL:fileURL];
BOOL ok = [migrationManager migrateStoreFromURL:sourceStoreURL
type:sourceStoreType
options:sourceStoreOptions
withMappingModel:mappingModel
toDestinationURL:destinationStoreURL
destinationType:destinationStoreType
destinationOptions:destinationStoreOptions
error:&error2];
[mappingModel release];
}
Notes
笔记
A mapping model ends in
cdm
in the bundle.The destination store has to be provided and should not be the source store. You can after successful migration delete the old and rename the new one.
I did some changes to the data model after the creation of the mapping models, this resulted in some compatibility errors, which I could only solve with recreating the mapping models.
映射模型以
cdm
束结束。必须提供目标商店,而不应该是源商店。您可以在成功迁移后删除旧的并重命名新的。
创建映射模型后,我对数据模型进行了一些更改,这导致了一些兼容性错误,我只能通过重新创建映射模型来解决。
回答by occulus
These questions are related:
这些问题是相关的:
Memory issues migrating large CoreData datastores on iPhone
在 iPhone 上迁移大型 CoreData 数据存储时出现内存问题
Multiple Pass Core Data Migration In Chunks With iOS
To quote the first link:
引用第一个链接:
This is discussed in the official documentation in the "Multiple Passes" section, however it looks like their suggested approach is to divide up your migration by entity type, i.e. make multiple mapping models, each of which migrate a subset of the entity types from the complete data model.
这在“Multiple Passes”部分的官方文档中进行了讨论,但是看起来他们建议的方法是按实体类型划分迁移,即创建多个映射模型,每个映射模型从完整的数据模型。
回答by PapaSmurf
Suppose your database schema has 5 entities, e.g. person, student, course, class, and registration to use the standard kind of example, where student subclasses person, class implements course, and registration joins class and student. If you have made changes to all these table definitions, you have to start at the base classes, and work your way up. So, you cannot start with converting registrations, because each registration record depends on having class and students there. So, you would start with migrating only the Person table, copying existing rows into the new table, and filling in whatever new fields are there (if possible) and discarding the removed columns. Do each migration inside an autorelease pool, so that once it is done, your memory is back to start.
假设您的数据库模式有 5 个实体,例如人、学生、课程、班级和注册,以使用标准类型的示例,其中学生子类人,班级实现课程,而注册加入班级和学生。如果您对所有这些表定义进行了更改,则必须从基类开始,然后逐步进行。因此,您不能从转换注册开始,因为每个注册记录都取决于那里的班级和学生。因此,您可以从仅迁移 Person 表开始,将现有行复制到新表中,并填充那里的任何新字段(如果可能)并丢弃已删除的列。在自动释放池中进行每次迁移,这样一旦完成,您的记忆就会重新开始。
Once the Person table is done, then you can convert the student table over. Then hop over to Course and then Class, and the finally the Registration table.
完成 Person 表后,您可以转换学生表。然后跳到课程,然后是课堂,最后是注册表。
The other consideration is the number of records, if like Person had a thousand rows, you would have to, every 100 or so, execute the NSManagedObject equivalent of a release, which is to tell the managed object context [moc refreshObject:ob mergeChanges:NO]; Also set your stale data timer way low, so that memory is flushed often.
另一个考虑是记录的数量,如果像 Person 有一千行,你就必须,每 100 行左右,执行一次 NSManagedObject 等价的释放,这是告诉托管对象上下文 [moc refreshObject:ob mergeChanges:不]; 还将您的陈旧数据计时器设置为低,以便经常刷新内存。