gpt4 book ai didi

objective-c - RestKit 手动保存对象

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:51:44 24 4
gpt4 key购买 nike

我花了几个小时尝试插入/添加对象,但发生了重复的记录。事件记录已重新插入,即使它已经存在。我错过了什么吗?

下面是我的代码:

广告系列.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];

已编辑 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];

最佳答案

是的,将 .primaryKeyAttribute 添加到您的映射中。当您通过 rest kit 导入数据时,这将为您完成 pk 工作。如果你只是用 Restkit 做“正常”的核心数据,你需要自己处理引用完整性等。

关于objective-c - RestKit 手动保存对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10384468/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com