3

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

一切正常,直到我删除 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];
}

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

我错过了什么?

4

2 回答 2

0

来自 Apple 文档:

If you set the value to NSManagedObjectIDResultType, this will demote any sort orderings to “best efforts” hints if you do not include the property values in the request.

您需要将所有更改写入持久存储或将 includePendingChanges 设置为 NO。

于 2014-11-21T11:25:20.290 回答
0

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

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

如果您想要这种行为,请使用获取结果控制器。它将维护您对数据库的期望视图。

于 2012-04-15T00:00:47.047 回答