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

sob*_*dio 5 iphone core-data ipad ios

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

核心数据

我想在对话上创建一个fetched属性,以返回属于它的最新消息.我不想保持另一种关系,所以拥有一个取得的财产似乎是要走的路.

那么归结为是什么;

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

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

Mar*_*rra 7

您可以使用fetched属性来解决该问题,但有一个问题.

无法在模型编辑器中定义该fetched属性.

可以在代码中定义该fetched属性.

所以,是的,你可以做到,但价值非常低.

更新

你有一个在代码中定义一个fetched属性的例子吗?我会在哪里这样做?managedObjectModel?

是的,你会通过这样做NSManagedObjectModel.

  1. 您必须在将模型添加到a之前进行编辑NSPersistentStoreCoordinator.一旦a 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");
Run Code Online (Sandbox Code Playgroud)

注意我在添加到NSFetchRequest之后如何设置.如果之后未进行设置,则会收到Core Data的错误消息.雷达已经提交,但我怀疑很少有人甚至看过这些东西,更不用说对这种奇怪的行为提出了雷达.NSFetchedPropertyNSEntityDescription