核心数据排序

时间:2017-06-22 08:45:16

标签: ios core-data

我有一些混合了String和Integer的数据,比如

"003G"
"002P"
"001P"
"018P"
"002G"
"019P"
"001G"
"020P"
"012P"
"011P"
"012G"
"013P"
"007P"
"011G"
"010P"
"009P"
"008P"
"005P"
"006P"
"014P"
"007G"
"010G"
"009G"
"008G"
"015P"
"006G"
"005Ga"
"004P"
"016P"
"005G"
"004G"
"003P"
"017P"

需要输出如:

"001P"
"002P"
"003P"
"004P"
"005P"
"006P"
"007P"
"008P"
"009P"
"010P"
"011P"
"012P"
"013P"
"014P"
"015P"
"016P"
"017P"
"018P"
"019P"
"020P"
"001G"
"002G"
"003G"
"004G"
"005G"
"005Ga"
"006G"
"007G"
"008G"
"009G"
"010G"
"011G"
"012G"

同时Android使用*[0-9,0P-9P,0G-9G]

完成排序

3 个答案:

答案 0 :(得分:2)

这是一个非常不寻常的排序顺序。您必须使用Comparator

编写自定义描述符

需要两个描述符。

  1. 按降序排列第四个字符

    let sortDescriptor1 = NSSortDescriptor(key: "referenceNo", ascending: false) { (obj1, obj2)  -> ComparisonResult in
        let string1 = obj1 as! String
        let string2 = obj2 as! String
        let fourthChar1 = string1.index(string1.startIndex, offsetBy: 3)
        let fourthChar2 = string2.index(string2.startIndex, offsetBy: 3)
        return String(string1[fourthChar1]).compare(String(string2[fourthChar2]))
    }
    
  2. 使用numeric选项对前3个字符进行排序并考虑xxxxa案例

    let sortDescriptor2 = NSSortDescriptor(key: "referenceNo", ascending: true) { (obj1, obj2)  -> ComparisonResult in
        let string1 = obj1 as! String
        let string2 = obj2 as! String
        let fourthChar1 = string1.index(string1.startIndex, offsetBy: 3)
        let fourthChar2 = string2.index(string2.startIndex, offsetBy: 3)
        let orderedResult = string1.substring(to: fourthChar1).compare(string2.substring(to: fourthChar2), options: .numeric)
        if orderedResult == .orderedSame {
            return string1.characters.count < string2.characters.count ? .orderedAscending : .orderedDescending
        } else {
            return orderedResult
        }
    }
    
  3. 当然,这假设值是ASCII范围内总是4个字符以上的字符串。

答案 1 :(得分:0)

NSArray *keysArray;  // your strings

将每个字符串放入数组并使用

下面的代码
NSArray *sortedArray = [keysArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

Apple为字母排序提供了几个选择器:

compare:
caseInsensitiveCompare:
localizedCompare:
localizedCaseInsensitiveCompare:
localizedStandardCompare:

答案 2 :(得分:0)

如果您使用NSFetchRequest查询核心数据,那么继续在fetchRequest上添加排序描述符,如下所示:

fetchRequest.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"referenceNo" ascending:YES selector:@selector(caseInsensitiveCompare:)]];