0

我有一个具有许多属性的核心数据实体,包括数量(浮点数)、类别总计(浮点数)和类别(字符串)

初始 ViewController 使用 FethchedResultsController 来检索实体,并根据类别对它们进行排序,然后是 categoryTotal。到目前为止没有问题。

NSManagedObjectContext *moc = [self managedObjectContext];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Transaction" inManagedObjectContext:moc];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:entityDescription];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(dateStamp >= %@) AND (dateStamp =< %@)", startDate, endDate];
[request setPredicate:predicate];

NSSortDescriptor *sortByCategory = [[NSSortDescriptor alloc] initWithKey:@"category" ascending:sortOrder];
NSSortDescriptor *sortByTotals = [[NSSortDescriptor alloc] initWithKey:@"categoryTotal" ascending:sortOrder];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortByTotals, sortByCategory, nil];
[request setSortDescriptors:sortDescriptors];

NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:managedObjectContext sectionNameKeyPath:@"category" cacheName:nil];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;

在选择一行时(tableView:didSelectRowAtIndexPath),另一个视图控制器被加载,允许编辑所选实体的金额字段。

在返回第一个视图之前,categoryTotal 被新的“金额”更新。当返回到第一个视图控制器时,问题就来了,应用程序炸弹

严重的应用程序错误。在核心数据更改处理期间捕获到异常:无效更新:第 0 节中的行数无效。更新后现有节中包含的行数 (1) 必须等于更新前该节中包含的行数(1),加上或减去从该部分插入或删除的行数(0 插入,1 删除)。with userInfo (null) 程序接收信号:“EXC_BAD_ACCESS”。

这似乎是由 NSSortDescriptor *sortByTotals = [[NSSortDescriptor alloc] initWithKey:@"categoryTotal" ascending:sortOrder]; 如果我删除它,一切都会按预期工作,但显然没有我想要的排序。

我猜这与由于 categoryTotal 更改(删除/插入)而导致的排序顺序更改有关,但无法解决此问题。我已经验证了在第二个视图中正确地修改了值,因此它似乎是 fetchedResultsController 被混淆了。如果 categoryAmount 更改为不改变排序顺序的,则不会产生错误

我没有在物理上更改(即删除)fetchedResultsController 返回的项目数......我能找到的唯一其他问题似乎会产生此错误

任何想法都将受到欢迎

谢谢, AJ

4

3 回答 3

3

The ordering of your managed objects via sectionNameKeyPath MUST match the ordering of your managed objects via your primary sort descriptor. Since you are using "category" as your sectionNameKeyPath and yet using "categoryTotal" as your primary sort descriptor, it will not be universally true that the sectionNameKeyPaths have the same ordering as the primary sort descriptor. The reason that removing sortByTotals fixes the problem is that "category" then becomes both the sectionNameKeyPath and the primary sort descriptor, and thus they both have the same ordering.

于 2010-03-27T08:56:18.133 回答
2

Try changing your sort in your NSFetchedResultsController to first sort by category and then by categoryTotal. This should resolve the issue. If it does not, please post your NSFetchedResultsController delegate methods.

于 2010-03-27T14:35:19.163 回答
0

如果categoryTotal是瞬态属性,则无法使用获取请求按此属性排序。您需要手动(通过代码)将 fetchedObjects 排序到可以在表中使用的第二个数组中。

于 2010-02-09T16:09:23.700 回答