NSSortDescriptor with arbitrary sorting

ぐ巨炮叔叔 提交于 2019-12-01 06:36:43
occulus

You need to pull out the first characters of obj1 and obj2 strings as NSStrings, find their indexes in your arbitrary ordering array, then compare the positions.

Something like this: (put this code in your ^ block)

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;

Not tested, may require a little tweaking. Watch out for upper/lower case character differences.

UPDATE: It seems there are problems with using custom sort descriptors and SQL backed core data stores. Please see this question for more info.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!