我从核心数据中获取了一些记录,并将其呈现在表格 View 中。所有这些记录都有 11 个属性。现在,在我的表格 View 演示文稿中,我在标题上添加了一个用于所有这些属性的按钮。单击按钮后,我想根据该属性对记录进行排序。 我尝试使用排序描述符,但它不起作用。 我的代码是这样的:-
- (IBAction)sortButton:(id)sender {
// tags are from 100 to 111
UIButton *sortButton = (UIButton*)sender;
NSString *sortDescriptorKey = nil;
// create sort descriptor key according to the tag value
if (sortButton.tag == 100 ) sortDescriptorKey = [NSString stringWithString:@"reportID "];
....
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:sortDescriptorKey ascending:YES];
[self.recordArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
[sortDescriptor release];
[self.tableView reloadData];
}
但是,这段代码根本不会改变任何顺序。 我是否遗漏了什么,或者是否有其他方法可以做到这一点。
最佳答案
问题出在这句话
[self.recordArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
这会返回 recordArray
的排序副本,但您没有使用它。您应该将其分配回recordArray
,以便tableView
在重新加载时正确更新。将其更改为:
self.recordArray=[self.recordArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
关于ios - 对 NSManaged 对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8710215/