gpt4 book ai didi

iphone - 需要 iPhone 核心数据中多对多关系的帮助

转载 作者:行者123 更新时间:2023-12-03 18:42:17 24 4
gpt4 key购买 nike

我当前的项目遇到了障碍。我基本上有一个非常类似于 Core Data Recipe 应用程序的应用程序......这是我的 .xcdatamodel 中的基本结构

实体:餐厅字符串:名称Category:类别<----对多关系

实体:类别字符串:名称Restaurant:餐厅<----对多关系所以基本上,一个餐厅可以有多个类别......并且有大量的预定义类别。例如:餐厅:名称: 辣椒分类: 外卖 , 家庭用餐

“外卖”和“家庭用餐”是 10 种可能的不同餐厅类别中的 2 种。我该怎么做呢..我已经查看了 sqllite 数据库,我有我的 ZRestaurant 和 ZCategory 表 + 它们两个的连接表...我在两者中都有数据...

如何使用不同的值设置我的餐厅类别?然后我如何取回它们?

谢谢大家!库尔特

最佳答案

好的,经过过去两天的研究,我终于想出了我的解决方案,它实际上是 Alex 和 Wills 建议的混合......谢谢你们俩!!

这是我所拥有的...

 NSManagedObjectContext *context = [restaurant managedObjectContext];


NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:[NSEntityDescription entityForName:@"Category" inManagedObjectContext:context]];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:&sortDescriptor count:1];
[fetchRequest setSortDescriptors:sortDescriptors];

NSError *error = nil;
NSArray *possibleCategories = [context executeFetchRequest:fetchRequest error:&error];

categoryArray = [[NSMutableArray alloc] initWithArray:possibleCategories];

currentCategories = [restaurant valueForKeyPath:@"categories"];

[restaurant addCategoriesObject:(Category *)[possibleCategories objectAtIndex:15 ]];

[currentCategories addObject:(Category*)[categoryArray objectAtIndex:15]];

然后我像这样保存

- (void)save{
NSLog(@"EditCatagoriesTableViewController - save");

NSSet* myCategorySet = [[NSSet alloc] initWithSet:currentCategories];

NSError *error = nil;

[restaurant addCategories:myCategorySet];


error = nil;
if (![restaurant.managedObjectContext save:&error]) {
// Handle error
NSLog(@"restaurant - Unresolved error %@, %@", error, [error userInfo]);
exit(-1); // Fail
}
}

就这样!

非常感谢两位的帮助!!!

-库尔特

关于iphone - 需要 iPhone 核心数据中多对多关系的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1449523/

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