gpt4 book ai didi

ios - 我可以使用 Core Data 获取的属性来返回最新的实体吗?

转载 作者:可可西里 更新时间:2023-11-01 04:29:48 31 4
gpt4 key购买 nike

我有两个实体有这样的关系......

Core Data

我想在对话中创建一个获取的属性以返回属于它的最新消息。我不想维持另一种关系,因此拥有一个获取的属性似乎是可行的方法。

所以这归结为;

如何将获取的属性限制为一项?

如何按时间戳对项目进行排序?

最佳答案

您可以使用获取的属性来解决该问题,但有一个问题。

不能在模型编辑器中定义该获取的属性。

可以在代码中定义该获取的属性。

所以是的,你可以做到,但值(value)很低。

更新

Have you got an example of defining a fetched property in code? Where would I do this? The managedObjectModel?

是的,您可以通过 NSManagedObjectModel 完成此操作。

  1. 您必须在将模型添加到 NSPersistentStoreCoordinator 之前进行编辑。一旦将 NSManagedObjectModel 添加到 NSPersistentStoreCoordinator,它就会变得不可变。

  2. 您获取您关心的实体,然后创建一个 NSFetchedPropertyDescription

  3. NSFetchedPropertyDescription 添加到现有实体。

  4. NSFetchRequest 添加到创建的 NSFetchedPropertyDescription

一旦完成,您就可以像平常一样使用 NSManagedObjectModel。除了必须进入不寻常的模型之外,非常简单。你做事的顺序很重要。举个例子:

NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Model" withExtension:@"momd"];
NSManagedObjectModel *mom = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
ZAssert(mom, @"%@:%@ No model to generate a store from", [self class], NSStringFromSelector(_cmd));

//Inject a fetched property
NSEntityDescription *parentEntity = [mom entitiesByName][@"Parent"];

NSFetchedPropertyDescription *fetchedProperty = [[NSFetchedPropertyDescription alloc] init];
[fetchedProperty setName:@"lastTestEntity"];

NSMutableArray *properties = [[parentEntity properties] mutableCopy];
[properties addObject:fetchedProperty];
[parentEntity setProperties:properties];

NSFetchRequest *testEntityRequest = [[NSFetchRequest alloc] init];
[testEntityRequest setEntity:[mom entitiesByName][@"TestEntity"]];
[testEntityRequest setPredicate:[NSPredicate predicateWithFormat:@"parent == $FETCH_SOURCE"]];
[testEntityRequest setFetchLimit:1];

NSSortDescriptor *sortByDate = [NSSortDescriptor sortDescriptorWithKey:@"createDate" ascending:NO];
[testEntityRequest setSortDescriptors:@[sortByDate]];

[fetchedProperty setFetchRequest:testEntityRequest];

NSPersistentStoreCoordinator *coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom];
ZAssert(coordinator, @"Failed to initialize coordinator");

请注意我是如何在 NSFetchedProperty 添加到 NSEntityDescription 之后设置 NSFetchRequest 的。如果你之后没有设置它,你将从核心数据中得到一个错误。雷达已经归档,但我怀疑很少有人看过这些东西,更不用说针对奇怪的行为提出雷达了。

关于ios - 我可以使用 Core Data 获取的属性来返回最新的实体吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24182584/

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