gpt4 book ai didi

iphone - 如何使用 Core Data 维护 UITableView 中的显示顺序?

转载 作者:行者123 更新时间:2023-12-03 18:27:58 25 4
gpt4 key购买 nike

在使用 UITableView 时,我在让核心数据实体正常运行和排序时遇到一些问题。

我已经在 StackOverflow 上浏览了许多教程和其他问题,但似乎没有一个清晰或优雅的方法来做到这一点 - 我真的希望我错过了一些东西。

我有一个核心数据实体,其上有一个名为“displayOrder”的 int16 属性。我使用已按“displayOrder”排序的 NSFetchRequest 来返回 UITableView 的数据。除了重新排序之外的一切都受到尊重。这是我的(低效的)moveRowAtIndePath 方法:

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {         

NSUInteger fromIndex = fromIndexPath.row;
NSUInteger toIndex = toIndexPath.row;

FFObject *affectedObject = [self.fetchedResultsController.fetchedObjects objectAtIndex:fromIndex];
affectedObject.displayOrderValue = toIndex;

[self FF_fetchResults];


for (NSUInteger i = 0; i < [self.fetchedResultsController.fetchedObjects count]; i++) {
FFObject *otherObject = [self.fetchedResultsController.fetchedObjects objectAtIndex:i];
NSLog(@"Updated %@ / %@ from %i to %i", otherObject.name, otherObject.state, otherObject.displayOrderValue, i);
otherObject.displayOrderValue = i;
}

[self FF_fetchResults];
}

任何人都可以为我指出一些示例代码的方向,或者看看我做错了什么吗? TableView 显示更新正常,我可以通过日志消息看到 displayOrder 属性正在更新。它只是不能始终如一地保存和重新加载,而且这种实现感觉非常“不正常”(除了我所有 FFObject 的浪费迭代)。

预先感谢您提供的任何建议。

最佳答案

我查看了您的代码,这可能会更好:

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {         

NSUInteger fromIndex = fromIndexPath.row;
NSUInteger toIndex = toIndexPath.row;

if (fromIndex == toIndex) {
return;
}

FFObject *affectedObject = [self.fetchedResultsController.fetchedObjects objectAtIndex:fromIndex];
affectedObject.displayOrderValue = toIndex;

NSUInteger start, end;
int delta;

if (fromIndex < toIndex) {
// move was down, need to shift up
delta = -1;
start = fromIndex + 1;
end = toIndex;
} else { // fromIndex > toIndex
// move was up, need to shift down
delta = 1;
start = toIndex;
end = fromIndex - 1;
}

for (NSUInteger i = start; i <= end; i++) {
FFObject *otherObject = [self.fetchedResultsController.fetchedObjects objectAtIndex:i];
NSLog(@"Updated %@ / %@ from %i to %i", otherObject.name, otherObject.state, otherObject.displayOrderValue, otherObject.displayOrderValue + delta);
otherObject.displayOrderValue += delta;
}

[self FF_fetchResults];
}

关于iphone - 如何使用 Core Data 维护 UITableView 中的显示顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1648223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com