6

在我的核心数据模型中,aPerson有一个或多个Cars,由无序对多关系“汽车”指定。通常,我需要检索由datePurchased或订购的人员的汽车dateLastUsed

到目前为止,我一直在将自己的方法添加到Personfor carsByDatePurchased。这使用排序描述符对 NSSet 进行排序cars并返回一个 NSArray。

我可以/应该为此使用 Fetched 属性吗?每次我需要按特定顺序的汽车时,我都会使用排序描述符遇到一些性能开销,甚至实现我自己的carsByDatePurchased. 看起来为我缓存了获取的属性 - 对吗?

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

至关重要的是,获取的属性值在执行之间是否持续存在?如果我更新获取的属性并保存我的上下文,是否会在下次启动应用程序时存储该值?

4

4 回答 4

4

获取的属性将起作用,实际上我在我自己的项目中使用了它,它具有需要按“添加日期索引”排序的 Post->Comment 关系。

有许多警告:您不能在可视化编辑器中指定排序描述符,而必须在代码中指定它。

我用这样的东西

    // 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

帖子有一对多“评论”关系,评论有“帖子”逆

与此处的其他答案相反:使用这样的获取属性的好处是,CoreData 负责缓存并使缓存无效,因为评论或拥有它们的帖子发生了变化。

于 2012-11-12T13:02:16.863 回答
2

如果您想获得一些性能,请使用 NSFetchedResultsController 进行获取并使其与缓存一起使用。下次您执行相同的提取时,提取会更快。在您的特定名称中,您将不得不缓存名称。查看 NSFetchedResultsController文档

于 2012-10-22T19:05:27.433 回答
1

获取的属性基本上是一个获取请求。我不知道如何在 GUI 中向这些属性添加排序描述符,但我可能错了。但是为什么不在你的carsByDatePurchased方法中创建一个获取请求并提供一个排序描述符呢?它返回一个数组或结果(您可以将其廉价地包装在设置为 no 的NSOrderedSet标志copyItems:中)。

于 2012-10-22T19:01:11.243 回答
0
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;
于 2017-02-27T13:32:17.730 回答