gpt4 book ai didi

iphone - 重新排列表格 View 单元格后如何更新 coredata 记录

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

我知道这个问题之前已经被问过,但是,我仍然对如何在核心数据项目中使用 UITableView 单元格实现重新排序感到困惑。下面提到的代码我在我的项目中使用来重新排列 TableView 单元格。重新排列单元格后,核心数据不受影响。

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath
toIndexPath:(NSIndexPath *)toIndexPath
{
NSInteger sourceRow = fromIndexPath.row;
NSInteger destRow = toIndexPath.row;
Question *cat1=[questionsArray objectAtIndex:sourceRow];
[questionsArray removeObjectAtIndex:sourceRow];
[questionsArray insertObject:cat1 atIndex:destRow];
[self.cardsTable setEditing:NO animated: YES];
[cardsTable reloadData];
}

最佳答案

如果您可以面向 iOS 5.0 及更高版本,那么您可以使用 NSOrderedSet 来维护对象的顺序。请记住,使用此方法的效率明显低于我在下面建议的其他方法(根据 Apple 的文档)。更多信息请查看Core Data Release Notes for iOS 5 .

如果您需要支持 5.0 之前的 iOS 版本或者想要使用更有效的方法,那么您应该在实体中创建一个附加的整数属性,并在添加实体对象时手动维护其中的索引或重新排列。当需要显示对象时,您应该根据这个新属性对它们进行排序,然后一切就完成了。例如,您的 moveRowAtIndexPath 方法应如下所示:

- (void)moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath sortProperty:(NSString*)sortProperty
{
NSMutableArray *allFRCObjects = [[self.fetchedResultsController fetchedObjects] mutableCopy];

NSManagedObject *sourceObject = [self.fetchedResultsController objectAtIndexPath:sourceIndexPath];

// Remove the object we're moving from the array.
[allFRCObjects removeObject:sourceObject];
// Now re-insert it at the destination.
[allFRCObjects insertObject:sourceObject atIndex:[destinationIndexPath row]];

// Now update all the orderAttribute values for all objects
// (this could be much more optimized, but I left it like this for simplicity)
int i = 0;
for (NSManagedObject *mo in allFRCObjects)
{
// orderAttribute is the integer attribute where you store the order
[mo setValue:[NSNumber numberWithInt:i++] forKey:@"orderAttribute"];
}
}

最后,如果您发现这太多的手动工作,那么我真的建议使用免费的 Sensible TableView框架。该框架不仅会自动为您维护顺序,还会根据您的实体的属性及其与其他实体的关系生成所有 TableView 单元格。在我看来,这绝对是一个很好的节省时间的方法。我还知道另一个名为 UIOrderedTableView 的库,但我自己从未使用过它,所以我不能推荐它(前一个框架也更受欢迎)。

关于iphone - 重新排列表格 View 单元格后如何更新 coredata 记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15630870/

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