我花了几个小时尝试插入/添加对象,但发生了重复的记录。即使已经存在,也会重新插入营销活动记录。我错过了什么吗?
以下是我的代码:
运动.h
@interface Campaign : NSManagedObject
@property (nonatomic, strong) NSNumber* campaignId;
@property (nonatomic, strong) NSString* title;
@end
卡片.h
@class Campaign;
@interface Card : NSManagedObject
@property (nonatomic, strong) NSNumber* cardId;
@property (nonatomic, strong) NSString* name;
@property (nonatomic, strong) Campaign* campaign;
@end
视图控制器.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];
编辑的 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];