简体   繁体   English

如何为核心数据实现自定义映射模型?

[英]How can I implement a custom mapping model for Core Data?

I've added a new entity (Site) to my Core Data Model, and a relationship to my old entity (Notification) pointing at Site. 我在核心数据模型中添加了一个新实体(站点),并指向了指向站点的旧实体(通知)建立了关系。 What I need to do is populate the new entity with a single object (the values for the attributes of the new object are in User Defaults right now), and then assign all of the old objects to the variable representing the relationship. 我需要做的是用一个对象填充新实体(新对象的属性值现在在“用户默认值”中),然后将所有旧对象分配给表示关系的变量。

The notifications variable on the Site object is one-to-many and optional. Site对象上的notifications变量是一对多的和可选的。 The site variable on the Notification object is one-to-one and required. 通知对象上的站点变量是一对一的并且是必需的。

My new object looks like so: 我的新对象看起来像这样:

#import <Foundation/Foundation.h>

@interface Site : NSManagedObject

@property (nonatomic, retain) NSString *url;
@property (nonatomic, retain) NSString *accessKey;
@property (nonatomic, retain) NSString *secretKey;
@property (nonatomic, retain) NSSet *notifications;

@end

The old object has a new 'site' attribute: 旧对象具有新的“站点”属性:

#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#import "Site.h"


@interface Notification : NSManagedObject

@property (nonatomic, retain) NSNumber *created;
@property (nonatomic, retain) NSNumber *isRead;
@property (nonatomic, retain) NSString *message;
@property (nonatomic, retain) NSNumber *notificationId;
@property (nonatomic, retain) NSString *url;
@property (nonatomic, retain) NSString *urlMarkRead;
@property (nonatomic, retain) Site *site;

@end

Any ideas how I can accomplish this? 有什么想法我可以做到这一点吗?

You can do a manual migration. 您可以进行手动迁移。 It's going to be some work for you to code that up, but it'll solve your problem. 编写代码将需要一些工作,但它将解决您的问题。

Take a look at the Core Data Versioning and Data Migration Programming Guide . 看一看《 核心数据版本控制和数据迁移编程指南》 There you'll find The Migration Process with a subsection called Custom Entity Migration Policies which describes your situation. 在这里,您会找到“迁移过程”,其中有一个名为“ 自定义实体迁移策略”的小节,它描述了您的情况。

You need to create a subclass of NSEntityMigrationPolicy . 您需要创建NSEntityMigrationPolicy的子类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM