开发者

Migrating from Dictionary to Core Data Entity

开发者 https://www.devze.com 2023-01-21 05:09 出处:网络
I\'ve got a data model where there is a Person entity, which has a transformable attribute which is an array of dictionaries containing information. The model is much bigger than that, this is just th

I've got a data model where there is a Person entity, which has a transformable attribute which is an array of dictionaries containing information. The model is much bigger than that, this is just the part I'm having trouble with. It was designed this way by an old developer, and in taking over the project I need to migrate this to be 100% core data.

So what I need to do is create a new entity, then step through each dictionary in the Person's array and create new instances of that entity with the information from that dictionary. I thought I could use an NSEntityMigrat开发者_JAVA百科ionPolicy to set up a custom migration for this new Entity, but it seems the Core Data migration is expecting X number of source entities to translate to X number of destination entities. Because I technically have 0 source entities right now (because they're in an array that Core Data doesn't really know anything about), I'm not sure how I can make the migration create new entities during the process.

What, or rather where in the migration procedure, is the best way to do what I'm trying to accomplish? I've always used lightweight migration in the past, so this is my first adventure in custom migration.


It would help to have a sense of your data model (schema) - but let's assume that your Person entity now holds home address and list of favorite restaurants. And let's further assume that you will be creating new entities Address and Restaurant along with the following relationships:

Person has one Address, so there's a to-one relationship from Person to Address called "homeAddress". There's an inverse to-many relationship from Address to Person, because many people could live at the same address.

Person has a to-many relationship (called restaurants) to Restaurants. Restaurant could also has a to-many relationship to Person (though this might be one of those cases where bidirectionality doesn't really make sense).

Anyway, the point is that now - in addition to your PersonToPerson NSEntityMigrationPolicy subclass, you will also have PersonToAddress and PersonToRestaurant. These will be the places that you unpack the old data and use it to instantiate and initialize new Address and Restaurant objects.

Of course, there are lots of other complicating issues. For example, you won't want to be creating a new instance of the same Restaurant for every Person who likes it. You will need to keep track of newly created Restaurants.

You will want to order your mappings strategically - probably with PersonToPerson first.

You might want to look at Marcus Zarra's Core Data sample code and maybe even buy his book.

0

精彩评论

暂无评论...
验证码 换一张
取 消