我有一个 UISegmentControl 和我的 UITableView 对数据进行排序。我希望能够做的事情:
(1) 默认排序(所以当用户第一次打开应用程序时,它会选择第一个段,并按该操作排序)
(2) 记住用户在表加载之间的位置。我的意思是,类似于 Apple 的封面流,当我转到不同的封面时,UITableView 会重新填充。因此,如果用户最后一次在那里,排序在第 3 段,那么它会记住这一点。
我对面向对象的设计有点陌生,这是我最好的猜测,不是到处都有相同的冗余代码:(MarkersList 是一个 NSMutableArray)
- (NSArray *)sortByName:(NSArray *)sortDescriptors {
return [self.MarkersList sortedArrayUsingDescriptors:sortDescriptors];
}
- (NSArray *)sortByRSID:(NSArray *)sortDescriptors {
return [self.MarkersList sortedArrayUsingDescriptors:sortDescriptors];
}
- (void)setSortedMarkersList:(NSArray *)sortedArray {
if (self.MarkersList != nil) {
[self.MarkersList removeAllObjects];
}
[self.MarkersList addObjectsFromArray:sortedArray];
}
- (IBAction)sortButtonPressed:(UISegmentedControl *)segmentControl {
// Create sort descriptors
NSSortDescriptor *nameDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"Name" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)] autorelease];
NSSortDescriptor *rsID = [[NSSortDescriptor alloc] initWithKey:@"ID" ascending:YES];
if ([segmentControl selectedSegmentIndex] == NAME) { // this is #define 0
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:nameDescriptor, rsIDDescriptor, nil];
NSArray *sortedArray = [self sortByGene:sortDescriptors];
[self setSortedMarkersList:sortedArray];
[sortDescriptors release];
}
else if ([segmentControl selectedSegmentIndex] == RS_ID) {
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:rsIDDescriptor, resultDescriptor, nameDescriptor, nil];
NSArray *sortedArray = [self sortByRSID:sortDescriptors];
[sortDescriptors release];
[self setSortedMarkersList:sortedArray];
}
[self.MarkersTableView reloadData];
}
我还没有实现第三种排序,因为它不仅仅是像其他两个那样的 NSString 或 NSNumber 。到目前为止,我认为它工作正常。但是,我遇到的问题是实现(1),我需要在加载表时调用 sortByName。我可以再次创建 NSSortDescriptors,但这似乎是多余的。有没有更OOD的方法来实现这一点?
对于(2),我猜我可以将表的索引保存在字典中,并在加载该表时检索它。或者类似的东西,不太确定。
任何帮助是极大的赞赏。谢谢!