核心数据中的获取属性

在我的核心数据模型中,一个Person有一个或多个Cars ,由无序的一对多关系“汽车”指定。 通常情况下,我需要检索按datePurchaseddateLastUsed订购的人车。

到目前为止,我已经将自己的方法添加到了carsByDatePurchased Person中。 这使用sorting描述符来sortingNSSet cars并返回一个NSArray。

可以/我应该使用一个Fetched属性吗? 每次我按照特定的顺序需要汽车时,我都会遇到一些使用sorting描述符的性能开销,即使实现我自己的carsByDatePurchasedcaching。 它看起来像获取的属性为我caching – 是正确的?

获取的属性与我自己的实现有什么限制?

关键是,被掠夺的财产的价值在执行之间是否持续? 如果我更新提取的属性并保存我的上下文,是下次启动应用程序时存储的值?

获取的属性将起作用,而且事实上我在我自己的项目中使用了“Post – > Comment”关系,该关系需要按“添加date索引”进行sorting。

有一些注意事项:你不能在可视化编辑器中指定sorting描述符,而必须在代码中指定它。

我使用这样的东西

  // Find the fetched properties, and make them sorted... for (NSEntityDescription *entity in [_managedObjectModel entities]) { for (NSPropertyDescription *property in [entity properties]) { if ([property isKindOfClass:[NSFetchedPropertyDescription class]]) { NSFetchedPropertyDescription *fetchedProperty = (NSFetchedPropertyDescription *)property; NSFetchRequest *fetchRequest = [fetchedProperty fetchRequest]; // Only sort by name if the destination entity actually has a "index" field if ([[[[fetchRequest entity] propertiesByName] allKeys] containsObject:@"index"]) { NSSortDescriptor *sortByName = [[NSSortDescriptor alloc] initWithKey:@"index" ascending:YES]; [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sortByName]]; } } } } 

在我的邮政实体,我有一个被称为“sortedComments”,被定义为:

 post == $FETCH_SOURCE 

post有一对多的“评论”关系,评论有一个“post”相反

与此处的其他答案相反:使用像这样的提取属性的好处是CoreData负责caching并使caching失效,因为对于post的评论或者确实是拥有它们的post发生了改变。

如果你想获得一些性能,使用NSFetchedResultsController进行获取,并使其与caching一起工作。 下次您执行相同的提取操作时,提取速度会更快。 用你的名字,你将不得不caching名字。 看看NSFetchedResultsController 文档 。

提取的属性基本上是一个提取请求。 我不知道如何添加sorting描述符到GUI中的这些属性,但我可能是错的。 但是,为什么不在你的carsByDatePurchased方法中创build一个获取请求,并提供一个sorting描述符? 它返回一个数组或结果(你可以用一个包含copyItems: flag的NSOrderedSet将其低成本地包装为no)。

 AppDelegate *delegate = [UIApplication sharedApplication].delegate; NSManagedObjectContext *context = [delegate managedObjectContext]; NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"DataRecord" inManagedObjectContext:context]; [fetchRequest setEntity:entity]; NSError *error; fetchedObjects = [context executeFetchRequest:fetchRequest error:&error]; for (NSManagedObject *obj in fetchedObjects) { NSLog(@"Name: %@", [obj valueForKey:@"name"]); NSLog(@"Info: %@", [obj valueForKey:@"info"]); NSLog(@"Number: %@", [obj valueForKey:@"number"]); NSLog(@"Create Date: %@", [obj valueForKey:@"createDate"]); NSLog(@"Last Update: %@", [obj valueForKey:@"updateDate"]); } NSManagedObject *obj = [fetchedObjects objectAtIndex:0]; [self displayManagedObject:obj]; selectedObject = obj;