CoreData实体类一对多

来源:互联网 发布:html连接access数据库 编辑:程序博客网 时间:2024/06/10 15:44

Core Data and Mantle – One-to-Many Relationship

I’ve been using Mantle and AFNetworking in so many projects in the past, I think it’s a wonderful combination which saves me a lot of time and makes extremely easy to write model layered iOS and OS X applications.

Parsing and consuming REST APIs makes a lot of sense, but what happens when you need to persist and use Core Data relationships. Well, it’s not trivial and the great news is that Mantle 1.5 supports Core Data and works great.

However we need to to a little extra work. Since model classes inherit from NSManagedObject, which means that they can’t inherit from MTLModel, we need to use  separated classes for Mantle and Core Data. So, we can start using Core Data as we know (Core Data data model and generated classes to support Relationships) and to get this work together we just need to add Mantle classes since we need to separate model hierarchy for any data represented as JSON.

Let’s start with a simple example, in this case we are going to use the classic relationship Playlists and Songs (One-to-Many).

The Setup

The first step is create the Core Data datamodel as usual, add the right entities, properties and relationships.

coredata_relationships

Playlist

coredata_relationships_playlist

Song

coredata_relationships_song

NSManagedObject subclasses


0 0
原创粉丝点击