RestKit 手动保存对象
Posted
技术标签:
【中文标题】RestKit 手动保存对象【英文标题】:RestKit save object manually 【发布时间】:2012-04-30 13:25:04 【问题描述】:我花了几个小时尝试插入/添加对象,但发生了重复记录。即使已经存在,也会重新插入营销活动记录。我错过了什么吗?
以下是我的代码:
Campaign.h
@interface Campaign : NSManagedObject
@property (nonatomic, strong) NSNumber* campaignId;
@property (nonatomic, strong) NSString* title;
@end
Card.h
@class Campaign;
@interface Card : NSManagedObject
@property (nonatomic, strong) NSNumber* cardId;
@property (nonatomic, strong) NSString* name;
@property (nonatomic, strong) Campaign* campaign;
@end
ViewController.m
...
Campaign* campaign = [Campaign object];
campaign.campaignId = [NSNumber numberWithInt:1];
campaign.title = @"Hello world";
Card* card = [Card object];
card.cardId = @"1234567890";
card.campaign = campaign;
[[[RKObjectManager sharedManager] objectStore] save:nil];
EDITED ViewController.m
...
RKManagedObjectMapping* cardMapping = [RKManagedObjectMapping mappingForClass:[Card class] inManagedObjectStore:[RKObjectManager sharedManager].objectStore];
[cardMapping mapKeyPath:@"id" toAttribute:@"cardId"];
[campaignMapping mapKeyPath:@"name" toAttribute:@"name"];
cardMapping.primaryKeyAttribute = @"cardId";
RKManagedObjectMapping* campaignMapping = [RKManagedObjectMapping mappingForClass:[Campaign class] inManagedObjectStore:[RKObjectManager sharedManager].objectStore];
[campaignMapping mapKeyPath:@"id" toAttribute:@"campaignId"];
[campaignMapping mapKeyPath:@"title" toAttribute:@"title"];
campaignMapping.primaryKeyAttribute = @"campaignId";
Campaign* campaign = [Campaign object];
campaign.campaignId = [NSNumber numberWithInt:1];
campaign.title = @"Hello world";
Card* card = [Card object];
card.cardId = @"1234567890";
card.campaign = campaign;
[[[RKObjectManager sharedManager] objectStore] save:nil];
【问题讨论】:
【参考方案1】:是的,将 .primaryKeyAttribute 添加到您的映射中。 当您通过 rest kit 导入数据时,这将为您完成 pk 工作。如果你只是用 Restkit 做“正常”的核心数据,你需要自己处理参照完整性等。
【讨论】:
我已经用 .primaryKeyAttribute 更新了我的代码(参见上面的编辑),但是我仍然在活动实体中得到重复的记录。它适用于 RKObjectManager loadObjectsAtResourcePath 但当我尝试手动添加对象时却不行。 是的。如果你只是在做核心数据的东西,你需要自己生成 ids(如果你想要的话)。你不需要它们,因为设置 card.campaign 将存储关系,核心数据有它自己的内部 id,除非你查看 sqlite 数据库,否则你看不到。您可能想要它们的唯一原因是,如果您正在同步到远程数据库并且想要与它们同步,但是如果您按照我所说的那样做,您需要自己在代码中进行。 另见***.com/questions/10264224/…以上是关于RestKit 手动保存对象的主要内容,如果未能解决你的问题,请参考以下文章
更新 RestKit:loadObjectsAtResourcePath:usingBlock:不要将对象保存在缓存中
如何在 RestKit 中保存到 Core Data RKMappingResult 对象?