gpt4 book ai didi

ios - 核心数据重复实体

转载 作者:行者123 更新时间:2023-11-29 13:07:22 25 4
gpt4 key购买 nike

我是 Core Data 的新手,我遇到了一些与多对多关系有关的问题,

这是我的结构

Diagrams

此结构允许 1 个 Profile 可以有多个 itens,1 个 Item 可以在多个 Profiles 中它就像一个商店

两种关系都是反向的

因此,当我在配置文件中添加新项目时,新项目在我的表项目中是重复的。

ITENS LIST
==========
ITEM9
ITEM50
==========

在配置文件中添加新项目后

ITENS LIST
==========
ITEM9
ITEM50
ITEM9
==========

当我列出我的个人资料时,“itens”是正确的,只有 1 个新项目。

PROFILE 
==========
ITEM9
==========

此操作的代码是。

MocManager* moc = [MocManager sharedMocManager];
NSArray* products = [moc listData:@"products"];
NSMutableString* desc = [NSMutableString string];

if( products != nil ) {
Item* itemToBuy = products[0]; // This is just a test. get the first
Item* newItem = [Item initItem];

NSEntityDescription *entity = [itemToBuy entity];
for (NSString *attributeName in [entity attributesByName]) {
[newItem setValue:[itemToBuy valueForKey:attributeName] forKey:attributeName];
}
for (NSString *relationshipName in [entity relationshipsByName]) {
[newItem setValue:[itemToBuy valueForKey:relationshipName] forKey:relationshipName];
}


[desc appendString:newItem.identifier];

[profile addItensObject:newItem];

[moc saveData];
}

我的问题是。

  • 我可以防止重复吗?

  • 如果无法阻止这种情况。我怎样才能只列出 Itens没有任何关联的配置文件?

感谢

布鲁诺

最佳答案

这是我检查重复项的方法:

ENTITY* obj = nil;
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"ENTITY"];
request.predicate = [NSPredicate predicateWithFormat:@"ENTITY.ID = %@", NEW_ELEMENT_ID];

NSError *error = nil;
NSArray *matches = [context executeFetchRequest:request error:&error];

if (!matches || ([matches count] > 1)) {
//NSLog(@"Error, YOU HAVE MORE THAN ONE OBJECT WITH SAME ID");
} else if ([matches count] == 0) {
//NSLog(@"NEW, OBJ NOT FOUND WITH THAT ID");
obj = [NSEntityDescription insertNewObjectForEntityForName:@"ENTITY" inManagedObjectContext:YOUR_CONTEXT];
} else {
obj = [matches lastObject]; //only one obj found... update this one
}

return obj;

关于ios - 核心数据重复实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18263502/

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