RestKit手动保存对象

时间:2012-04-30 13:25:04

标签: objective-c ios core-data restkit

我花了几个小时尝试插入/添加对象,但发生了重复记录。即使已存在,也会重新插入广告系列记录。我错过了什么吗?

以下是我的代码:

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 个答案:

答案 0 :(得分:1)

是的,将.primaryKeyAttribute添加到您的映射中。 当你通过rest kit导入数据时,这将为你做pk的东西。如果您只是使用Restkit执行“正常”核心数据,则需要自己处理参考整合等。