CoreData:仅获取最后一个元素,而不是所有(iPhone) [英] CoreData: fetch only last elements, not all (iPhone)

查看:122
本文介绍了CoreData:仅获取最后一个元素,而不是所有(iPhone)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

欢迎

我使用Core Data来存储数据。我需要这样一个方法,只返回实体的最后7个元素。我的问题是我应该如何修改这个代码(它获取所有的元素,但我只需要最后7)

i use Core Data to store datas. i need such a method which returns only the last 7 elements of entity. my question is how should i modify this code ( it fetchs all of elements, but i need only last 7)

    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Trip" inManagedObjectContext:managedObjectContext];
NSFetchRequest *request = [[ NSFetchRequest alloc] init];
[request setEntity:entity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"distance" ascending:NO]; 
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];  
[request setSortDescriptors:sortDescriptors];  
[sortDescriptor release];  
NSError *error;  
tripArray = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];


推荐答案

核心数据在内部没有订单的概念。如果您是根据您的距离属性最远的距离,您可以执行以下操作:

Define last? Core Data does not have a concept of order internally. If you mean by the farthest away based on your distance property then you can do the following:

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Trip" inManagedObjectContext:managedObjectContext];
NSFetchRequest *request = [[ NSFetchRequest alloc] init];
[request setEntity:entity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"distance" ascending:NO]; 
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];  
[request setSortDescriptors:sortDescriptors];  
[request setFetchLimit:7];
[sortDescriptor release];  
NSError *error;  
NSArray *tripArray = [managedObjectContext executeFetchRequest:request error:&error];

请注意,添加 -setFetchLimit:将导致此请求仅返回7个结果。它将返回第一7基于您的排序。所以,如果你想要最接近的,逆向升序:部分你的排序。

Note that the addition of the -setFetchLimit: will cause this request to only return 7 results. It will return the "first" 7 based on your sort. So if you want the closest, reverse the ascending: portion of your sort.

-mutableCopy -executeFetchRequest:error:返回的$ c> c $ c> NSArray 。添加对象到 NSArray 将不会将它们添加到Core Data中,并从 NSArray 中删除​​它们不会从Core数据。因此,它绝对没有价值,只是浪费。

There is absolutely no point in calling -mutableCopy on the NSArray that is returned from -executeFetchRequest: error:. Adding objects to that NSArray will not add them to Core Data and removing them from that NSArray will not remove them from Core Data. Therefore it has absolutely no value and is just wasteful.

你还记得你在哪里看到了吗?我一直在试图跟踪它一段时间。

Do you remember where you saw that? I have been trying to track it down for a while now.

这篇关于CoreData:仅获取最后一个元素,而不是所有(iPhone)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆