NSSortDescriptor与任意sorting
我无法将自己的头围绕如何使用NSSortDescriptor进行任意sorting。
我想要做这样的事情:
NSArray *sortAlgorithm = [NSArray arrayWithObjects:@"@", @"#", @"!", @"&", @"r", @"a", nil]; NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES comparator: ^(id obj1, id obj2) { NSComparisonResult comparisonResult; //Some code that uses sortAlgorithm. return comparisonResult; } ];
这将通过键name
对对象进行sorting,以便任何以@
开始的键(例如@home
)将出现在任何以r
开头的键之前(例如radical
,并且再次以任何以a
开头的键。
以上只是一个例子。 关键是要启用完全的任意sorting。
这将用于NSFetchedResultsController。
什么代码//使用sortAlgorithm的一些代码看起来像?
编辑:
代码围绕我尝试实现sortDescriptor,作为公关。 occulus'
build议:
- (NSFetchedResultsController *)fetchedResultsController { if (__fetchedResultsController) return __fetchedResultsController; NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; fetchRequest.entity = [NSEntityDescription entityForName:@"Tag" inManagedObjectContext:self.temporaryManagedObjectContext]; //NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO]; NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO comparator:^(id obj1, id obj2) { NSArray *sortAlgorithm = [NSArray arrayWithObjects:@"#", @"!", @"@", @".", nil]; NSString *obj1FirstChar = [(NSString *)obj1 substringToIndex:1]; NSString *obj2FirstChar = [(NSString *)obj2 substringToIndex:1]; int idx1 = [sortAlgorithm indexOfObject:obj1FirstChar]; int idx2 = [sortAlgorithm indexOfObject:obj2FirstChar]; if ( idx1 < idx2 ) return NSOrderedAscending; else if ( idx1 > idx2 ) return NSOrderedDescending; else return NSOrderedSame; }]; fetchRequest.sortDescriptors = [NSArray arrayWithObject:sortDescriptor]; fetchRequest.fetchBatchSize = 20; NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.temporaryManagedObjectContext sectionNameKeyPath:nil cacheName:@"Tags"]; aFetchedResultsController.delegate = self; self.fetchedResultsController = aFetchedResultsController; [self.fetchedResultsController performFetch:nil]; return __fetchedResultsController; }
注释的sortDescriptor工作。
在实体“标签”的对象上肯定有一个名为name
的属性。 但即使没有,这似乎不是问题。 Xcode似乎甚至没有编译那行代码(sortDescriptor),这听起来很荒谬。 断点工作得很好,但不会破坏特定的代码行。
您需要将obj1
和obj2
string的第一个字符作为NSStrings
取出,在您的任意sorting数组中find它们的索引,然后比较位置。
就像这样:(把这个代码放在你的^
块中)
NSString *obj1FirstChar = [(NSString *)obj1 substringToIndex:1]; NSString *obj2FirstChar = [(NSString *)obj2 substringToIndex:1]; int idx1 = [sortAlgorithm indexOfObject:obj1FirstChar]; int idx2 = [sortAlgorithm indexOfObject:obj2FirstChar]; // NOTE: we haven't dealt with the case where one of the // chars wasn't found in the array of characters. A strategy // for this would need to be decided. if (idx1 == idx2) { return NSOrderedSame; } if (idx1 < idx2) { return NSOrderedAscending; } return NSOrderedDescending;
未经testing,可能需要稍微调整。 注意大写/小写字符的差异。
更新:似乎有使用自定义sorting描述符和SQL支持核心数据存储的问题。 请参阅此问题以获取更多信息。