objective-c - IOS Core 数据获取请求 - 排序

标签 objective-c ios core-data

我正在使用后台线程来获取有限数量的按日期排序的记录。

一切正常,直到我在 UI 线程(tableview)中删除一条记录。

//this is done in the background thread
NSFetchRequest *frequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"MyEntity" 
                                            inManagedObjectContext:self.managedObjectContext];
[frequest setEntity:entity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]
                                    initWithKey:@"date"     
                                    ascending:NO];

NSArray *descriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[frequest setSortDescriptors:descriptors];

[frequest setFetchOffset:fetchOffset];    
[frequest setFetchLimit:20];

[frequest setResultType:NSManagedObjectIDResultType];

 NSError *fetchError;
 NSMutableArray *mutableFetchResults = [[self.managedObjectContext executeFetchRequest:frequest 
                                                                               error:&fetchError] mutableCopy];

后台线程为NSManagedObjectContextDidSaveNotification注册并执行下面的选择器

//this is done in the background thread
-(void) didSavePersistenceStore:(NSNotification *)notification
{
    [self.managedObjectContext mergeChangesFromContextDidSaveNotification:notification];
}

问题:删除一条记录后,后续fetch结果不再按日期排序。

我错过了什么?

最佳答案

首先,确保您没有从错误的线程中使用 managedObjectContext。您可以调用 performBlock 在适当的上下文中执行此操作。

其次,您用于提取的提取描述符不会持续存在。因此,除非您继续使用相同的排序标准进行抓取,否则您将无法获得它。

如果您想要这种行为,请使用获取结果 Controller 。它将维护您想要的数据库 View 。

关于objective-c - IOS Core 数据获取请求 - 排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10158345/

相关文章:

ios - 为什么 Apple 在 Recipes 代码示例中同时使用私有(private)变量和同名属性?

ios - 随机文本(Objective-c)

iphone - NSSortDescriptor 去除 "the"前缀

ios - 使用 TableViewController 发送到实例的无法识别的选择器

iphone - XCode 的管理器无法显示正确的包显示名称

ios - 如何在 Swift 中将本地时间日期转换为 UTC?

ios - 在 CollectionView 的 didSelectItemAtIndexPath 方法中获取 CGPoint

ios - 当原型(prototype)单元不工作时如何使用 segue

iphone - CoreData prepareForDeletion 被调用无限次

ios - 使用魔法记录的核心数据迁移